-- SPDX-License-Identifier: GPL-3.0-or-later

local extension = Package:new("old1")
-- extension.extensionName = "vupslash"
extension.extensionName = "VslTest"
-- extension.game_modes_whitelist = { 'nos_heg_mode', 'new_heg_mode' }
-- dofile "packages/vupslash/game_rule.lua"

-- local VslUtil = require "packages/vupslash/util"
local VslUtil = require "packages/VslTest/util"

--------------------------------------------------
--测试技能：超级控制
--------------------------------------------------

local v_control = fk.CreateActiveSkill{
  name = "v_control",
  anim_type = "control",
  can_use = Util.TrueFunc,
  card_filter = Util.FalseFunc,
  card_num = 0,
  target_filter = function(self, to_select)
    return to_select ~= Self.id
  end,
  min_target_num = 1,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    for _, pid in ipairs(effect.tos) do
      local to = room:getPlayerById(pid)
      if to:getMark("mouxushengcontrolled") == 0 then
        room:addPlayerMark(to, "mouxushengcontrolled")
        from:control(to)
      else
        room:setPlayerMark(to, "mouxushengcontrolled", 0)
        to:control(to)
      end
    end
  end,
}

--------------------------------------------------
--测试技能：超级英姿
--------------------------------------------------

local super_yingzi = fk.CreateTriggerSkill{
  name = "superyingzi",
  anim_type = "drawcard",
  events = {fk.DrawNCards},
  on_use = function(self, event, target, player, data)
    data.n = data.n + 20
  end,
}

--------------------------------------------------
--测试技能：摸指定牌
--------------------------------------------------

local v_cheat = fk.CreateActiveSkill{
  name = "v_cheat",
  anim_type = "drawcard",
  can_use = function(self, player)
    return true
  end,
  on_use = function(self, room, effect)
    local from = room:getPlayerById(effect.from)
    local cardTypeName = room:askForChoice(from, { 'basic', 'trick', 'equip' }, "cheat")
    local cardType = Card.TypeBasic
    if cardTypeName == 'trick' then
      cardType = Card.TypeTrick
    elseif cardTypeName == 'equip' then
      cardType = Card.TypeEquip
    end

    local allCardIds = Fk:getAllCardIds()
    local allCardMapper = {}
    local allCardNames = {}
    for _, id in ipairs(allCardIds) do
      local card = Fk:getCardById(id)
      if card.type == cardType then
        if allCardMapper[card.name] == nil then
          table.insert(allCardNames, card.name)
        end

        allCardMapper[card.name] = allCardMapper[card.name] or {}
        table.insert(allCardMapper[card.name], id)
      end
    end

    if #allCardNames == 0 then
      return
    end

    local cardName = room:askForChoice(from, allCardNames, "cheat")
    local toGain = nil
    if #allCardMapper[cardName] > 0 then
      toGain = allCardMapper[cardName][math.random(1, #allCardMapper[cardName])]
    end

    from:addToPile(self.name, toGain, true, self.name)
    room:obtainCard(effect.from, toGain, true, fk.ReasonPrey)
  end
}

--------------------------------------------------
--测试技能：流失体力
--------------------------------------------------

local v_lose = fk.CreateActiveSkill{
  name = "v_lose",
  anim_type = "offensive",
  can_use = function(self, player)
    return true
  end,
  target_num = 1,
  -- card_num = 1,
  card_filter = function(self, to_select, selected, selected_targets)
    return false
    -- if #selected == 1 then return false end
    -- return Fk:currentRoom():getCardArea(to_select) ~= Player.Equip
  end,
  target_filter = function(self, to_select, selected)
    -- local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:loseHp(target, 1, self.name)
  end,
}

--------------------------------------------------
--嗜甜
--------------------------------------------------

local v_shitian = fk.CreateTriggerSkill{
  name = "v_shitian",
  --默认播放配音，可以通过Mute=true关闭技能配音。
  mute = true,
  --赋予支援型技能定义
  anim_type = "support", 
  --时机：阶段开始时
  events = {fk.EventPhaseStart}, 
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能、遍历到的角色处于准备阶段。
  can_trigger = function(self, event, target, player, data) 
    return target == player and player:hasSkill(self) and
      player.phase == Player.Start
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  -- on_cost = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   return true
  --   --end
  -- end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    --播放技能语音
    room:notifySkillInvoked(player, self.name)
    player:broadcastSkillInvoke(self.name)
    local judge = {} ---@type JudgeStruct
    judge.who = player
    --这一条的意思是，出现以下两种花色条件后显示判定成功的特效
    judge.pattern = ".|.|heart,diamond"
    judge.reason = self.name
    room:judge(judge)

    if judge.card.color == Card.Red then
      player:drawCards(1, self.name)
      --考虑到本作存在治疗过量概念，不需要角色受伤也可触发回复效果。
      --if player:isWounded() then 
      room:recover{
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
      --彩蛋标签准备
      room:setPlayerMark(player, "v_shitian_failed", 0)
      room:delay(500)
    else  --触发彩蛋
      if player:getMark("v_shitian_failed") >= 1 then
        local address = "./packages/"..VslUtil.extensionName.."/image/anim/v_shitian_failed"
        room:setEmotion(player, address)
      else
        room:addPlayerMark(player, "v_shitian_failed", 1)
      end
    end
  end,
}

--------------------------------------------------
--藏聪
--------------------------------------------------

local v_cangcong = fk.CreateTriggerSkill{
  name = "v_cangcong",
  --赋予防御型技能定义
  anim_type = "defensive",
  --时机：目标确定后
  events = {fk.TargetConfirmed},
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能、牌的种类为杀/锦囊牌、牌的目标>1。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      (data.card.name == "slash" or (data.card.type == Card.TypeTrick and
      data.card.sub_type ~= Card.SubtypeDelayedTrick)) and
      #AimGroup:getAllTargets(data.tos) > 1
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  -- on_cost = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   return true
  --   --end
  -- end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local address = "./packages/"..VslUtil.extensionName.."/image/anim/skill_nullify"
    room:setEmotion(player, address)
    table.insert(data.nullifiedTargets, player.id)
  end,
}

--------------------------------------------------
--绫奈奈奈
--------------------------------------------------

local lingnainainai_fentujk = General(extension, "lingnainainai_fentujk", "psp", 3, 3, General.Female)
lingnainainai_fentujk:addSkill(v_shitian)
lingnainainai_fentujk:addSkill(v_cangcong)

--------------------------------------------------
--抽卡
--技能马克：解锁隐藏巫女豹与戦的代码；
--------------------------------------------------

local v_chouka = fk.CreateTriggerSkill{
  name = "v_chouka",
  --赋予摸牌型技能定义
  anim_type = "drawcard",
  --时机：阶段开始时
  events = {fk.EventPhaseStart},
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能、遍历到的角色处于摸牌阶段。
  can_trigger = function(self, event, target, player, data)
    return (target == player and player:hasSkill(self) and player.phase == Player.Draw)
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  -- on_cost = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   return true
  --   --end
  -- end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    --记录已判定的花色
    local used_suit = {}
    local used_suit_show = {}
    local dummy = Fk:cloneCard('slash', Card.NoSuit, 0)
    while true do
      local all_suit = {"spade", "heart", "club", "diamond"}
      for _, s in ipairs(used_suit) do table.removeOne(all_suit, s) end
      local pattern = ".|.|" .. (#all_suit == 0 and "none" or table.concat(all_suit, ","))
      local judge = {
        who = player,
        reason = self.name,
        pattern = pattern,
      }
      room:judge(judge)
      local suit = judge.card:getSuitString()
      -- local suit_show = judge.card:getSuitString() .. "_char"
      if table.contains(used_suit, suit) then
        return true
      else
        table.insert(used_suit, suit)
        table.insert(used_suit_show, VslUtil.card_suits_table[suit])
        dummy:addSubcard(judge.card)
      end
      local prompt_suit = table.concat(used_suit_show, "+")
      -- local prompt_suit = used_suit_show
      local prompt = "v_chouka_choice_log:::"..prompt_suit
      -- local prompt = "v_chouka_choice_log1+"..prompt_suit.."+v_chouka_choice_log2"
      local choices = {"v_chouka_repeat", "v_chouka_stop"}
      local choice = room:askForChoice(player, choices, self.name, prompt)
      local address = "./packages/"..VslUtil.extensionName.."/image/anim/haibao"
      --点击取消，退出判定。
      if choice == "v_chouka_stop" then
        room:obtainCard(player.id, dummy, true)
        if #(dummy.subcards) >= 3 then
          room:setEmotion(player, address)
          --getThread暂无此代码，因此先注释掉。
          room:delay(360)
          room:setEmotion(player, address)
          if #(dummy.subcards) >= 4 then
            --为玩家记录可解锁角色，由于暂无本功能，先注释掉
            --RecordUnlockGenerals(player, "baishenyao_weiwunv")
            room:delay(360)
            room:setEmotion(player, address)
            room:delay(360)
            room:setEmotion(player, address)
          end
        end
        room:delay(500)
        break
      end
    end
  end,
}

--------------------------------------------------
--慵懒
--------------------------------------------------

local v_yonglanHelper = fk.CreateTriggerSkill{
  name = "#v_yonglanHelper",
  refresh_events = {fk.TargetConfirming},
  can_refresh = function(self, event, target, player, data)
    --print(data.card.number)
    return (target == player and player:hasSkill(self))
  end,
  on_refresh = function(self, event, target, player, data)
    local card = data.card
    local room = player.room
    if card.trueName == "slash" and card.number > 0 and card.id > 0 then
      --print(card.number)
      room:setPlayerMark(player, "v_yonglan_currentSlash", card.number)
    else
      room:setPlayerMark(player, "v_yonglan_currentSlash", 999)
    end
  end
}
local v_yonglan = fk.CreateViewAsSkill{
  name = "v_yonglan",
  anim_type = "defensive",
  pattern = "jink",
  card_filter = function(self, to_select, selected)
    if #selected == 1 then return false end
    return Fk:getCardById(to_select).number > Self:getMark("v_yonglan_currentSlash")
      and Fk:currentRoom():getCardArea(to_select) ~= Player.Equip
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then
      return nil
    end
    local c = Fk:cloneCard("jink")
    c:addSubcard(cards[1])
    return c
  end,
  enabled_at_response = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) < 1
  end,
}
v_yonglan:addRelatedSkill(v_yonglanHelper)

--------------------------------------------------
--白神遥
--角色马克：抽卡
--------------------------------------------------

local baishenyao_zhaijiahaibao = General(extension, "baishenyao_zhaijiahaibao", "psp", 3, 3, General.Female)
baishenyao_zhaijiahaibao:addSkill(v_chouka)
baishenyao_zhaijiahaibao:addSkill(v_yonglan)

local v_moci = fk.CreateTriggerSkill{
  name = "v_moci",
  mute = true,
  anim_type = "offensive",
  events = {fk.EventPhaseStart,fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if not (target == player and player:hasSkill(self)) then 
      return false 
    end
    if event == fk.EventPhaseStart then
      return player.phase == Player.Play 
        and not player:isKongcheng()
    elseif event == fk.TargetSpecified then
      return data.from and data.from == player.id
        and #player:getPile(self.name.."-pile!t*") > 0
        and room:getPlayerById(data.to):getHandcardNum() <= #player:getPile(self.name.."-pile!t*")
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.TargetSpecified then
      local room = player.room
      data.disresponsiveList =data.disresponsiveList or {}
      local targets = table.filter(table.map(room:getAlivePlayers(),function(p) return p.id end),
        function(p1) return (not table.contains(data.disresponsiveList,p1))
          and #player:getPile(self.name.."-pile!t*") > #room:getPlayerById(p1):getCardIds(Player.Hand)
      end)
      if #targets > 0 then
        self.cost_data = targets
        return true
      end 
    elseif event == fk.EventPhaseStart then
      local cards = player.room:askForCard(player, 1, 999, false, self.name, true, ".", "#v_moci_put")
      if #cards > 0 then
        self.cost_data = cards
        return true
      end
    end  
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      -- local cards = player.room:askForCard(player, 1, 999, false, self.name, true, ".", "#v_moci_put")
      -- if #cards > 0 then
      room:notifySkillInvoked(player, self.name)
      player:broadcastSkillInvoke(self.name)
      VslUtil.BanishCards_Table(player, player, self.cost_data, self.name.."-pile!t*", true)
        -- player:addToPile(self.name.."-pile!t*", cards, true, self.name)
      -- end
    elseif event == fk.TargetSpecified then
      if data.firstTarget then
        room:notifySkillInvoked(player, self.name)
        player:broadcastSkillInvoke(self.name)
      end
      data.disresponsiveList = data.disresponsiveList or {}
      table.insertTableIfNeed(data.disresponsiveList, self.cost_data) 
    end
  end,
}

--------------------------------------------------
--赤息
--------------------------------------------------

local v_chixi_Invalidity = fk.CreateInvaliditySkill {
  name = "#v_chixi_invalidity",
  invalidity_func = function(self, from, skill)
    if from:getMark("@@v_chixi-turn") ~= 0 then
      return not skill:isEquipmentSkill()
    end
  end
}

local v_chixi = fk.CreateTriggerSkill{
  name = "v_chixi",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.EventPhaseChanging},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.to == Player.Start
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if p.hp > p.maxHp/2 then
        room:setPlayerMark(p, "@@v_chixi-turn", 1)
      end
    end
  end,

  refresh_events = {fk.HpChanged},
  can_refresh = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(self) and player.phase ~= Player.NotActive
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if target:getMark("@@v_chixi-turn") ~= 0 and target.hp <= target.maxHp/2 then
      room:setPlayerMark(target, "@@v_chixi-turn", 0)
    elseif target:getMark("@@v_chixi-turn") == 0 and target.hp > target.maxHp/2 then
      room:setPlayerMark(target, "@@v_chixi-turn", 1)
    end    
  end,
}

v_chixi:addRelatedSkill(v_chixi_Invalidity)

--------------------------------------------------
--红晓音
--------------------------------------------------

local hongxiaoyin_heilangniao = General(extension, "hongxiaoyin_heilangniao", "psp", 4, 4, General.Female)
hongxiaoyin_heilangniao:addSkill(v_moci)
hongxiaoyin_heilangniao:addSkill(v_chixi)

--------------------------------------------------
--礼崩
--------------------------------------------------

local v_libeng = fk.CreateTriggerSkill{
  name = "v_libeng",
  -- mute = true,
  anim_type = "offensive",
  events = {fk.CardEffectCancelledOut},
  --使用条件：
  --...
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    return target == player and player:hasSkill(self)
      and data.card and data.card.trueName == "slash"
      and not room:getPlayerById(data.to):isKongcheng()
      and not player:isKongcheng()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local prompt = "v_libeng_choice::"..data.to
    if room:askForSkillInvoke(player, self.name, data, prompt) then
      return true
    end
    --   end
    -- end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(data.to)
    local pindian = player:pindian({tar}, self.name)
    if pindian.results[data.to].winner == player then
      room:damage{
        from = player,
        to = tar,
        damage = 1,
        damageType = fk.FireDamage,
        skillName = self.name,
      }
    else
      room:drawCards(player, 2, self.name)
    end
  end,
}

--------------------------------------------------
--超度
--------------------------------------------------

local v_chaodu_invalidity = fk.CreateInvaliditySkill {
  name = "#v_chaodu_invalidity",
  invalidity_func = function(self, from, skill)
    local purifying = false
    -- death-deathed的过度阶段防冥土追魂，通过currentroom调getallplayers崩了，
    -- 和currentroom的本质有关，它很可能会调取的是ClientInstance而非roominstance（大概）
    -- 结合client里room的表进行了修改。
    local room = Fk:currentRoom()
    local players = room.players
    -- local players = room.alive_players
    for _,p in ipairs(players) do
      local id = p:getMark("@v_chaodu_invalidity")
      if from.id == id then
        purifying = true
      end
    end
    return (from:getMark("@@v_chaodu_invalidity") > 0 or purifying)
      and not skill.attached_equip
  end
}

local v_chaodu = fk.CreateTriggerSkill{
  name = "v_chaodu",
  anim_type = "support",
  events = {fk.Death},
  can_trigger = function(self, event, target, player, data)
    return target ~= player and player:hasSkill(self) and not player.dead
      and data.damage 
      and not data.damage.card
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local choiceList = {}
    if player:isWounded() then 
      table.insert(choiceList, "recover_1")
    end
    if not target:isAllNude() then
      table.insert(choiceList, "v_chaodu_getcard")
    end
    -- table.insert(choiceList, "draw_2")
    table.insert(choiceList, "v_chaodu_counter")
    table.insert(choiceList, "cancel")
    local choice = room:askForChoice(player, choiceList, self.name)
    if choice == "cancel" then
      return false
    elseif choice == "recover_1" then
      self.cost_data = 1
    elseif choice == "v_chaodu_getcard" then
      self.cost_data = 2
    elseif choice == "v_chaodu_counter" then
      self.cost_data = 3
    end
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if self.cost_data == 1 then
      room:recover{
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
    elseif self.cost_data == 2 then
      -- player:drawCards(2, self.name)
      local allcards = {}
      table.insertTable(allcards, target:getCardIds(Player.Hand))
      table.insertTable(allcards, target:getCardIds(Player.Equip))
      table.insertTable(allcards, target:getCardIds(Player.Judge))
      local to_return = table.random(allcards, 1)
      local choice = "confirm"
      local get, top
      local result = room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseCardsAndChoiceBox.qml", {
        allcards,
        {"confirm"},
        "#v_chaodu_select",
        {},
        1,
        1,
      })
      if result ~= "" then
        local reply = json.decode(result)
        to_return = reply.cards
        choice = reply.choice
      end
      if to_return[1] and to_return[1] ~= -1 then
        local idcard = Fk:getCardById(to_return[1])
        room:obtainCard(player, idcard, true, fk.ReasonPrey)
      end
    elseif self.cost_data == 3 then
      room:setPlayerMark(player, "@v_chaodu_invalidity", target.id)
      -- room:setPlayerMark(target, "@@v_chaodu_invalidity", 1)
    end
  end,
}
local v_chaodu_deathed = fk.CreateTriggerSkill{
  name = "#v_chaodu_deathed",
  --时机：目标离场后
  refresh_events = {fk.Deathed},
  --触发条件：触发时机的角色为遍历到的角色
  can_refresh = function(self, event, target, player, data)
    return player:getMark("@v_chaodu_invalidity") == target.id
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@v_chaodu_invalidity", 0)
    room:setPlayerMark(target, "@@v_chaodu_invalidity", 1)
  end,
}

v_chaodu:addRelatedSkill(v_chaodu_invalidity)
v_chaodu:addRelatedSkill(v_chaodu_deathed)

--------------------------------------------------
--秋凛子
--角色马克：
--------------------------------------------------

local qiulinzi_wangyinwunv = General(extension, "qiulinzi_wangyinwunv", "psp", 4, 4, General.Female)
qiulinzi_wangyinwunv:addSkill(v_libeng)
qiulinzi_wangyinwunv:addSkill(v_chaodu)
-- qiulinzi_wangyinwunv:addSkill(v_cheat)
-- qiulinzi_wangyinwunv:addSkill(v_control)

--------------------------------------------------
--卓识
--------------------------------------------------

local v_zhuoshi_card = fk.CreateActiveSkill{
  name = "#v_zhuoshi_card",
  anim_type = "drawcard",
  min_target_num = function(self)
    if self.interaction.data == "v_zhuoshi_give_card" then
      return 1
    elseif self.interaction.data == "v_discard_1" then
      return 0
    end
  end,
  max_target_num = 1,
  min_card_num = 1,
  interaction = function(self)
    local types = Self:getMark("v_zhuoshi-turn")
    local v_zhuoshi_choice = {"v_discard_1"}
    if type(types) ~= "table" or #types < 3 then
      table.insert(v_zhuoshi_choice, "v_zhuoshi_give_card")
    end
    return UI.ComboBox {
      choices = v_zhuoshi_choice
    } 
  end,
  can_use = function(self, player)
    return player:isAlive() and not player:isNude()
  end,
  card_filter = function(self, to_select, selected, targets)
    if self.interaction.data == "v_zhuoshi_give_card" then
      local types = Self:getMark("v_zhuoshi-turn")
      local card_or_not = true
      for _,p in ipairs(selected) do
        if Fk:getCardById(p).type == Fk:getCardById(to_select).type then
          card_or_not = false
          break
        end
      end
      if type(types) == "table" then
        return card_or_not and not table.contains(types, Fk:getCardById(to_select):getTypeString())
      else
        return card_or_not
      end
    elseif self.interaction.data == "v_discard_1" then
      return #selected == 0 and ( not Self:prohibitDiscard(Fk:getCardById(to_select)) )
    end
  end,
  target_filter = function(self, to_select, selected, cards)
    if self.interaction.data == "v_zhuoshi_give_card" then
      return #selected == 0 and to_select ~= Self.id
    elseif self.interaction.data == "v_discard_1" then
      return false
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = nil
    -- 如果存在目标，则为交牌；否则必定为弃牌。
    if effect.tos[1] then
      target = room:getPlayerById(effect.tos[1])
      local types = player:getMark("v_zhuoshi-turn")
      local types_show = player:getMark("@v_zhuoshi_show-turn")
      -- 更新已经交出去的牌的标记
      if type(types) ~= "table" then
        types = {}
      end
      for _,p in ipairs(effect.cards) do
        table.insertIfNeed(types, Fk:getCardById(p):getTypeString())
      end
      --刷新显示用标记
      types_show = {}
      if table.contains(types, "basic") then
        table.insert(types_show, VslUtil.short_card_type["basic"])
      end
      if table.contains(types, "trick") then
        table.insert(types_show, VslUtil.short_card_type["trick"])
      end
      if table.contains(types, "equip") then
        table.insert(types_show, VslUtil.short_card_type["equip"])
      end
      --设定标记
      room:setPlayerMark(player, "v_zhuoshi-turn", types)
      room:setPlayerMark(player, "@v_zhuoshi_show-turn", types_show)
      --交牌
      room:moveCards({
        ids = effect.cards,
        from = player.id,
        to = target.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonGive,
      })
    else
      --弃牌
      room:moveCards({
        ids = effect.cards,
        from = player.id,
        toArea = Card.DiscardPile,
        moveReason = fk.ReasonDiscard,
      })
    end
  end,
}
local v_zhuoshi = fk.CreateTriggerSkill{
  name = "v_zhuoshi",
  --赋予摸牌型技能定义
  anim_type = "drawcard",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：宣告手牌使用时
  events = {fk.AfterCardUseDeclared},
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能
  --         牌的类型为锦囊牌
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) 
    and data.card.type == Card.TypeTrick
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,

  on_use = function(self, event, target, player, data)
    local room = player.room
    local types = player:getMark("v_zhuoshi-turn")
    local bas = 0
    local tri = 0
    local equ = 0
    if type(types) == "table" then
      if table.contains(types, "basic") then
        bas = 1
      end
      if table.contains(types, "trick") then
        tri = 1
      end
      if table.contains(types, "equip") then
        equ = 1
      end
    end
    local next_str = ""
    local type_str = "v_zhuoshi_type_" .. (bas + tri*2 + equ*4)
    if type_str ~= "v_zhuoshi_type_7" then
      next_str = "v_zhuoshi_can_give"
    end
    local prompt = "#v_zhuoshi_cardask:::"..next_str..":"..type_str
    player:drawCards(1, self.name)
    room:askForUseActiveSkill(player, "#v_zhuoshi_card", prompt, false)
  end,
}

v_zhuoshi:addRelatedSkill(v_zhuoshi_card)

--------------------------------------------------
--法棍
--技能马克：伪实现写好了，完全实现还需要一些时间。
--------------------------------------------------

local v_fagun = fk.CreateTriggerSkill{
  --（刚需）技能认证名
  name = "v_fagun",
  --(非必要）赋予防御型技能定义
  anim_type = "defensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：卡牌移动后，受到伤害时
  events = {fk.AfterCardsMove, fk.DamageInflicted},
  --触发条件：
  -- 卡牌移动后：
  --  触发时机的角色为遍历到的角色、遍历到的角色具有本技能、
  --  遍历到的角色不处于notactive状态、
  --  牌的移动来源存在且为遍历到的角色、牌移动原因为弃置
  --  检索牌堆后，发现存在红色基本牌
  --  不存在特定标记。
  -- 受到伤害时：
  --  触发时机的角色为遍历到的角色、遍历到的角色具有本技能、
  --  造成的伤害大于0、存在牌、牌的颜色为红色、
  --  存在特定标记。
  can_trigger = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      if player:hasSkill(self) and player:getMark("@@v_fagun_effect") == 0 then
        for _, move in ipairs(data) do
          if move.from and move.from == player.id and move.moveReason == fk.ReasonDiscard and player.phase ~= Player.NotActive then
            for _, info in ipairs(move.moveInfo) do
              local dis_card = Fk:getCardById(info.cardId)
              if dis_card:getColorString() == "red" and dis_card.type == Card.TypeBasic then
                return true
              end
            end
          end
        end
      end
    elseif event == fk.DamageInflicted then
      return target == player and player:hasSkill(self) 
        and data.damage > 0 and data.card and data.card.color == Card.Red 
        and player:getMark("@@v_fagun_effect") ~= 0
    end
  end,
  --使用流程：
  -- 卡牌移动后：
  --   为遍历到的角色提供特定标记
  -- 受到伤害时：
  --  return true
  on_use = function(self, event, target, player, data)
    --遍历全场所有存活角色，挑出其中未被横置的角色。
    local room = player.room
    if event == fk.AfterCardsMove then
      room:setPlayerMark(player, "@@v_fagun_effect", 1)
    elseif event == fk.DamageInflicted then
      return true
    end
  end,

  -- 由于标记类型特殊，在eventphasechanging需要刷新标签。
  -- 触发时机：from为notacitve；to不为notactive；存在特定标记。
  refresh_events = {fk.EventPhaseChanging},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("@@v_fagun_effect") ~= 0 
      and data.from == Player.NotActive and data.to ~= Player.NotActive
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@@v_fagun_effect", 0)
  end,
}

--------------------------------------------------
--YY
--角色马克：
--------------------------------------------------

local yizhiyy_mianbaoren = General(extension, "yizhiyy_mianbaoren", "psp", 4, 4, General.Male)
yizhiyy_mianbaoren:addSkill(v_zhuoshi)
yizhiyy_mianbaoren:addSkill(v_fagun)

--------------------------------------------------
--逐猎
--------------------------------------------------

local v_zhulie = fk.CreateTargetModSkill{
  name = "v_zhulie",
  residue_func = function(self, player, skill, scope, card)
    if player:hasSkill(self) 
      and card
      and card.color == Card.Red 
      and scope == Player.HistoryPhase then
      return 999
    end
  end,
  distance_limit_func =  function(self, player, skill, card)
    if player:hasSkill(self) 
      and card
      and card.color == Card.Black then
      return 999
    end
  end,
}

--------------------------------------------------
--混音
--------------------------------------------------

local v_hunyin = fk.CreateTriggerSkill{
  name = "v_hunyin",
  --赋予进攻型技能定义
  anim_type = "offensive",
  --时机：阶段开始时，目标指定后
  events = {fk.EventPhaseStart, fk.TargetSpecified},
  --触发条件：(已完成)
  --（阶段开始时）触发时机的角色为遍历到的角色；遍历到的角色具有本技能；
  --              被遍历到的角色处于回合开始阶段；
  --              牌堆中的牌>=2张；
  --（目标指定时）触发时机的角色为遍历到的角色；遍历到的角色具有本技能；
  --              遍历到的角色具有某种标记。
  --              使用的牌为杀
  --              本次流程中第一次触发这个时机
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      return target == player and player:hasSkill(self)
      and player.phase == Player.Start
      and #room.draw_pile >= 2
    elseif event == fk.TargetSpecified then
      return target == player and player:hasSkill(self)
      and player:getMark("@@v_hunyin_buff-turn") > 0
      and data.card.trueName == "slash"
      -- and data.firstTarget
    end
  end,
  on_cost = function(self, event, target, player, data)
    --确认是否发动技能。
    if event == fk.EventPhaseStart then
      local room = player.room
      if room:askForSkillInvoke(player, self.name, data) then
        return true
      end
    --满足技能发动要求后，锁定发动。
    elseif event == fk.TargetSpecified then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      --牌堆顶展示两张牌。【完成】
      local ids = {}
      for i = 1, 2, 1 do
        table.insert(ids, room.draw_pile[i])
      end
      player:showCards(ids)
      --比较两张牌的颜色，根据颜色决定是否增加BUFF标记。【完成】
      if Fk:getCardById(ids[1]).color ~= Fk:getCardById(ids[2]).color then
        room:addPlayerMark(player, "@@v_hunyin_buff-turn", 1)
        room:sendLog{
          type = "#v_hunyin_log",
          from = player.id,
          arg = self.name,
          arg2 = "v_hunyin_different",
        }
      elseif Fk:getCardById(ids[1]).color == Fk:getCardById(ids[2]).color then
        room:sendLog{
          type = "#v_hunyin_log",
          from = player.id,
          arg = self.name,
          arg2 = "v_hunyin_same",
        }
      end
      --询问是否弃牌。【完成】
      local prompt = "v_hunyin_throw_choice"
      if room:askForSkillInvoke(player, self.name, data, prompt) then
        -- room:throwCard(ids, self.name, player, player)
        room:moveCards({
          ids = ids,
          from = player.id,
          toArea = Card.DiscardPile,
          skillName = self.name,
          moveReason = fk.ReasonPutIntoDiscardPile,
          proposer = player.id
        })
        room:sendLog{
          type = "#v_hunyin_throw_log",
          from = player.id,
          arg = 2,
        }
      end
    --你使用的【杀】不可被【闪】响应【完成】
    elseif event == fk.TargetSpecified then
      data.disresponsive = true
    end
  end,
}

--------------------------------------------------
--莲汰
--------------------------------------------------

local liantai_bingyuanlangwang = General(extension, "liantai_bingyuanlangwang", "psp", 4, 4, General.Male)
liantai_bingyuanlangwang:addSkill(v_zhulie)
liantai_bingyuanlangwang:addSkill(v_hunyin)

--------------------------------------------------
--薄纱
--------------------------------------------------

local v_baosha_prohibit = fk.CreateProhibitSkill{
  name = "#v_baosha_prohibit",
  is_prohibited = function(self, from, to, card)
    if to:hasSkill("v_baosha") then
      return true
    end
  end,
}
local v_baosha = fk.CreateTriggerSkill{
  name = "v_baosha",
  --赋予防御型技能定义
  anim_type = "defensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：阶段变化时
  events = {fk.EventPhaseChanging},
  --触发条件：
  --触发时机的角色为遍历到的角色、遍历到的角色具有本技能；
  --上一阶段为不活跃阶段，下一阶段不为不活跃阶段。
  can_trigger = function(self, event, target, player, data)
    local change = data
    return target == player and player:hasSkill(self) 
    and change.from == Player.NotActive and change.to ~= Player.NotActive
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  -- on_cost = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   return true
  --   --end
  -- end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:handleAddLoseSkills(player, "-v_baosha", nil, true)
  end,
}

v_baosha:addRelatedSkill(v_baosha_prohibit)

--------------------------------------------------
--衔尾
--------------------------------------------------

local v_xianwei = fk.CreateViewAsSkill{
  name = "v_xianwei",
  --赋予摸牌型技能定义
  anim_type = "drawcard",
  pattern = "ex_nihilo",
  card_filter = function(self, to_select, selected)
    local room = Fk:currentRoom()
    local pls = room.players
    local pp = nil
    --通过是否处于出牌阶段确认是否是该玩家。
    for _,p in ipairs(pls) do
      if p.phase == Player.Play then
        pp = p
      end
    end
    if #selected < pp:getMark("@v_xianwei_count-phase") +1 and (not VslUtil.is_jilei(pp, Fk:getCardById(to_select))) then
      return true
    end
    return false
  end,
  view_as = function(self, cards)
    local room = Fk:currentRoom()
    local pls = room.players
    local pp = nil
    --通过是否处于出牌阶段确认是否是该玩家。
    for _,p in ipairs(pls) do
      if p.phase == Player.Play then
        pp = p
      end
    end
    if #cards ~= ( pp:getMark("@v_xianwei_count-phase") +1 ) then
      return nil
    end
    local c = Fk:cloneCard("ex_nihilo")
    for _,cd in ipairs(cards) do
			c:addSubcard(cd)
		end
    c.skillName = self.name
    return c
  end,
  enabled_at_play = function(self, player)
    local miya = Fk:currentRoom():getPlayerById(player:getMark("v_xianwei_m"))
    return VslUtil.is_wounded(miya)
  end,
}
local v_xianwei_mark = fk.CreateTriggerSkill{
  name = "#v_xianwei_mark",
  mute = true,
  priority = 11,
  anim_type = "drawcard",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then
      return false
    end
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      room:setPlayerMark(player, "v_xianwei_m", player.id)
      --print(player:getMark("v_xianwei_m"))
    end
  end,
}
local v_xianwei_count = fk.CreateTriggerSkill{
  name = "#v_xianwei_count",
  anim_type = "drawcard",

  refresh_events = {fk.PreCardUse},
  can_refresh = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if data.card.skillName == "v_xianwei" then
      -- if table.contains(data.card.skillNames, "v_xianwei") then
        return true
      end
    end 
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player, "@v_xianwei_count-phase", 1)
  end,
}
v_xianwei:addRelatedSkill(v_xianwei_mark)
v_xianwei:addRelatedSkill(v_xianwei_count)

--------------------------------------------------
--星猫
--------------------------------------------------

local v_xingmao_prohibit = fk.CreateProhibitSkill{
  name = "#v_xingmao_prohibit",
  is_prohibited = function(self, from, to, card)
    return false
  end,
  prohibit_use = function(self, player, card)
    return player:getMark("@@v_xingmao_prohibit_slash-turn") > 0 
      and card.type == Card.TypeBasic
  end,
}
local v_xingmao = fk.CreateTriggerSkill{
  name = "v_xingmao",
  anim_type = "defensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if not (target == player and player:hasSkill(self)) then return false end
    local use = data
    if use.card.name == "jink" and use.toCard and use.toCard.trueName == "slash" then
      local effect = use.responseToEvent
      return effect.to == player.id
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local effect = data.responseToEvent
    local slasher = room:getPlayerById(effect.from)
    room:setPlayerMark(slasher, "@@v_xingmao_prohibit_slash-turn", 1)
  end,
}

v_xingmao:addRelatedSkill(v_xingmao_prohibit)

--------------------------------------------------
--星之谷米娅
--------------------------------------------------

local xingzhigumiya_mengmao = General(extension, "xingzhigumiya_mengmao", "psp", 2, 3, General.Female)
xingzhigumiya_mengmao:addSkill(v_baosha)
xingzhigumiya_mengmao:addSkill(v_xianwei)
xingzhigumiya_mengmao:addSkill(v_xingmao)

--------------------------------------------------
--咏星
--------------------------------------------------

local v_yongxing = fk.CreateTriggerSkill{
  --（刚需）技能认证名
  name = "v_yongxing",
  --(非必要）赋予摸牌型技能定义
  anim_type = "drawcard",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：造成伤害后
  events = {fk.Damage},
  --触发条件：
  --存在触发时机的角色、触发时机的角色为遍历到的角色、遍历到的角色具有本技能、造成伤害的角色为遍历到的角色。
  can_trigger = function(self, event, target, player, data)
    local damage = data
    return target and target == player and player:hasSkill(self) and
      damage.from == player
  end,
  on_trigger = function(self, event, target, player, data)
    for i = 1, data.damage do
      self:doCost(event, target, player, data)
    end
  end,
  -- on_cost = function(self, event, target, player, data)
  --   for i = 1, data.damage do
  --     return true
  --   end
  -- end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,
}

--------------------------------------------------
--扬歌
--------------------------------------------------

local v_yangge = fk.CreateTriggerSkill{
  name = "v_yangge",
  --赋予支援型技能定义
  anim_type = "support",
  --时机：阶段开始时
  events = {fk.EventPhaseStart},
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能，遍历到的角色处于结束阶段，出牌阶段未被跳过，
  --         本回合未造成伤害、技能未失效（见on_trigger）。
  can_trigger = function(self, event, target, player, data)
    --阶段变化时，实现“是否跳出牌”的效果。
    --exist_or_not：用来确认是否跳过对应阶段，类似于以前的Player:isSkipped()
    return target == player and player:hasSkill(self) 
    and player.phase == Player.Finish and VslUtil.exist_or_not(player, Player.Play) 
    and player:getMark("#turn_damage-turn") == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local prompt = "#v_yangge_ask"
    local peach_or_not = room:askForCard(player, 1, 1, false, self.name, true, ".", prompt)[1]
    --print(peach_or_not)
    if peach_or_not then
      room:throwCard(peach_or_not, self.name, player)
      local god_salvation = Fk:cloneCard("god_salvation")
      local new_use = {} ---@type CardUseStruct
      new_use.from = player.id
      new_use.tos = {}
      new_use.card = god_salvation
      new_use.skillName = self.name
      for _,p in ipairs(room:getAlivePlayers()) do
        if not player:isProhibited(p, new_use.card) then
      	  table.insert(new_use.tos, { p.id })
        end
      end
      if not VslUtil.is_jilei(player, new_use.card) then
      	room:useCard(new_use)
      end
    else
      player:turnOver()
      local savage_assault = Fk:cloneCard("savage_assault")
      local new_use = {} ---@type CardUseStruct
      new_use.from = player.id
      new_use.tos = {}
      new_use.card = savage_assault
      new_use.skillName = self.name
      for _,p in ipairs(room:getOtherPlayers(player)) do
        if not player:isProhibited(p, new_use.card) then
      	  table.insert(new_use.tos, { p.id })
        end
      end
      if not VslUtil.is_jilei(player, new_use.card) then
      	room:useCard(new_use)
      end
    end
  end,
}

--------------------------------------------------
--东爱璃
--角色马克：
--------------------------------------------------

local dongaili_xingtu = General(extension, "dongaili_xingtu", "psp", 3, 3, General.Female)
dongaili_xingtu:addSkill(v_yongxing)
dongaili_xingtu:addSkill(v_yangge)

--------------------------------------------------
--雅和
--------------------------------------------------

--- 雅和观星。
---@param player ServerPlayer @ 玩家
---@param skillName string @ 技能名
local function v_yahe_guanxing(player, skillName)
	local room = player.room
	local card_ids = room:getNCards(4)
	room:askForGuanxing(player, card_ids, {4, 4}, {0, 0}, skillName, false)
end

--- 雅和摸牌。
---@param player ServerPlayer @ 玩家
---@param skillName string @ 技能名
local function v_yahe_draw(player, skillName)
	local room = player.room
	local min_handcard_num = player:getHandcardNum()
	-- 筛选最少手牌
	for _,p in ipairs(room:getOtherPlayers(player)) do
		if p:isAlive() and p:getHandcardNum() < min_handcard_num then
			min_handcard_num = p:getHandcardNum()
		end
	end
	-- 摸牌
	for _,p in ipairs(room:getAllPlayers()) do
		--后续看情况这里可以写player:caneffect()
		if p:isAlive() and p:getHandcardNum() == min_handcard_num then
			p:drawCards(1, skillName)
		end
	end
end

local v_yahe = fk.CreateTriggerSkill{
	name = "v_yahe",
	--默认播放配音，可以通过Mute=true关闭技能配音。
	mute = true,
	--赋予控制型技能定义
	anim_type = "control", 
	--时机：阶段开始时
	events = {fk.EventPhaseStart}, 
	--触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能.
	--          遍历到的角色处于准备阶段;
	--					遍历到的角色处于结束阶段且雅和已发动;
	can_trigger = function(self, event, target, player, data) 
		return target == player and player:hasSkill(self) 
			and (player.phase == Player.Start 
			or (player.phase == Player.Finish and player:getMark("@v_yahe-turn") > 0))
	end,
	-- on_trigger = function(self, event, target, player, data)
	--   --if self:isEffectable(player) then
	--   self:doCost(event, target, player, data)
	--   --end
	-- end,
	on_cost = function(self, event, target, player, data)
		--if self:isEffectable(player) then
		local room = player.room
		-- for i = 1, data.damage do
		if player.phase == Player.Start then
			local choiceList = {}
			table.insert(choiceList, "v_yahe1")
			table.insert(choiceList, "v_yahe2")
			table.insert(choiceList, "cancel")
			local choice = room:askForChoice(player, choiceList, self.name, "v_yahe_choice_log")
			if choice == "cancel" then
				self.cost_data = "cancel"
				return false
			elseif choice == "v_yahe1" then
				self.cost_data = 1
			elseif choice == "v_yahe2" then
				self.cost_data = 2
			end
			return true
		elseif player.phase == Player.Finish then
			return true
		end
		-- end
		-- end
	end,
	on_use = function(self, event, target, player, data)
		local room = player.room
		if player.phase == Player.Start then
			room:notifySkillInvoked(player, self.name)
			player:broadcastSkillInvoke(self.name)
			if self.cost_data == 1 then
				room:setPlayerMark(player, "@v_yahe-turn", 1)
				v_yahe_guanxing(player, self.name)
			elseif self.cost_data == 2 then
				room:setPlayerMark(player, "@v_yahe-turn", 2)
				v_yahe_draw(player, self.name)
			end
		elseif player.phase == Player.Finish then
			room:notifySkillInvoked(player, self.name)
			player:broadcastSkillInvoke(self.name)
			if player:getMark("@v_yahe-turn") == 1 then
				room:setPlayerMark(player, "@v_yahe-turn", 0)
				v_yahe_draw(player, self.name)
			elseif player:getMark("@v_yahe-turn") == 2 then
				room:setPlayerMark(player, "@v_yahe-turn", 0)
				v_yahe_guanxing(player, self.name)
			end
		end
	end,
}

--------------------------------------------------
--埋薯
--问题：
-- 1. 观星框里看不到土豆标记——还要再确认下
-- 对应调整方案：将原牌丢虚空，然后复制一张牌再在上面贴BUFF，参考智哲（据说用的是额外UI）
--------------------------------------------------

local v_maishu_explosion = fk.CreateTriggerSkill{
  --（刚需）技能认证名
  name = "#v_maishu_explosion",
	mute = true,
  --(非必要）赋予特殊型技能定义
  anim_type = "special",
  --时机：卡牌移动后
  events = {fk.AfterCardsMove},
  --触发条件：
	-- ...
  can_trigger = function(self, event, target, player, data)
		local room = player.room
		for _, move in ipairs(data) do
			if 
				(not room:getTag("FirstRound"))
				and move.to and move.to == player.id and move.moveReason == fk.ReasonDraw and move.toArea == Player.Hand 
				then
				for _, info in ipairs(move.moveInfo) do
					local card = Fk:getCardById(info.cardId)
					if card:getMark("@@v_potato_mine-cm!d*") > 0
						-- and card.area == Card.PlayerHand and room:getCardOwner(info.cardId) == player
						then
						return true
					end
				end
			end
		end
  end,
	on_cost = function(self, event, target, player, data)
		return true
  end,
  --使用流程：
  -- 卡牌移动后：
  --  ...
  on_use = function(self, event, target, player, data)
    --遍历全场所有存活角色，挑出其中未被横置的角色。
    local room = player.room
		-- local dummy = Fk:cloneCard("dilu")
		local cards = {}
		local cids = {}
		for _, move in ipairs(data) do
			if 
				(not room:getTag("FirstRound"))
				and move.to and move.to == player.id and move.moveReason == fk.ReasonDraw and move.toArea == Player.Hand then

				for _, info in ipairs(move.moveInfo) do
					local card = Fk:getCardById(info.cardId)
					if card:getMark("@@v_potato_mine-cm!d*") > 0
						-- and card.area == Card.PlayerHand and room:getCardOwner(info.cardId) == player 
						then
						table.insertIfNeed(cards, card)
						table.insertIfNeed(cids, info.cardId)
					end
				end
			end
		end
    if #cards > 0 then
			-- dummy:addSubcards(cards)
			room:sendLog{
				type = "#v_maishu_trigger",
				to = { player.id },
				card = cids,
				arg = "@@v_potato_mine-cm!d*",
			} 
      room:throwCard(cids, self.name, player, player)
			room:damage{
				to = player,
				damage = 1,
				damageType = fk.ThunderDamage,
				skillName = self.name,
			}
      -- local address = "./packages/"..VslUtil.extensionName.."/image/anim/v_potato_mine"
			-- room:setEmotion(player, address)
    end
  end,
}
local v_maishu = fk.CreateActiveSkill{
  name = "v_maishu",
	mute = true,
  anim_type = "special",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
		-- return true
  end,
  target_num = 0,
  card_num = 1,
  card_filter = function(self, to_select, selected, selected_targets)
    return Fk:getCardById(to_select).color == Card.Black
    -- if #selected == 1 then return false end
    -- return Fk:currentRoom():getCardArea(to_select) ~= Player.Equip
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
		local cid = effect.cards[1]
		room:notifySkillInvoked(player, self.name)
		player:broadcastSkillInvoke(self.name, -1)
		VslUtil.return_draw_pile(player, {cid}, self.name)
		room:setCardMark(Fk:getCardById(cid), "@@v_potato_mine-cm!d*", 1)
  end,
}
v_maishu:addRelatedSkill(v_maishu_explosion)

--------------------------------------------------
--笙歌
--------------------------------------------------

local shengge_wuxiugewu = General(extension,"shengge_wuxiugewu", "novus", 3, 3, General.Female)
shengge_wuxiugewu:addSkill(v_yahe)
shengge_wuxiugewu:addSkill(v_maishu)

--------------------------------------------------
--袭穴
--技能马克：失去技能后对标记的处理可以在一键删除姬里面处理。
--------------------------------------------------

local v_xixue = fk.CreateTriggerSkill{
  name = "v_xixue",
  --赋予摸牌型技能定义
  anim_type = "drawcard",
  -- --时机：手牌结算后
  -- events = {fk.CardUseFinished},
  --时机：宣告手牌使用时
  events = {fk.AfterCardUseDeclared},
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能、遍历到的角色处于出牌阶段、满足技能条件
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      player.phase == Player.Play and self.can_xixue
  end,
  on_use = function(self, event, target, player, data)
    player:drawCards(1, self.name)
  end,

  --refresh_events = {fk.CardUseFinished, fk.EventPhaseStart},
  refresh_events = {fk.AfterCardUseDeclared},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    self.can_xixue = VslUtil.suit_close(data.card.suit) == player:getMark("#v_xixue_mark-phase")
    room:setPlayerMark(player, "#v_xixue_mark-phase", data.card.suit)
    room:setPlayerMark(player, "@v_xixue_mark-phase", data.card:getSuitString())
  end,
}

--------------------------------------------------
--小千村鼬鼬
--角色马克：袭穴
--------------------------------------------------

local xiaoqiancunyouyou_yaolingbaiyou = General(extension,"xiaoqiancunyouyou_yaolingbaiyou", "novus", 3, 3, General.Female)
xiaoqiancunyouyou_yaolingbaiyou:addSkill(v_xixue)

--------------------------------------------------
--病缚
--旧写法在技能失效的时候无法消除技能效果
--目前实际效果耦合进util的受伤判定中
--------------------------------------------------

local v_bingfu = fk.CreateTriggerSkill{
  name = "v_bingfu",
  -- anim_type = "special",
  -- --技能为锁定技，满足条件后强制发动
  -- frequency = Skill.Compulsory,
  -- events = {fk.GameStart},
  -- can_trigger = function(self, event, target, player, data)
  --   if not player:hasSkill(self.name) then
  --     return false
  --   end
  --   return true
  -- end,
  -- on_use = function(self, event, target, player, data)
  --   local room = player.room
  --   if event == fk.GameStart then
  --     room:setPlayerMark(player, "v_wounded_chained", 1)
  --   end
  -- end,
}

--------------------------------------------------
--灵黯
--------------------------------------------------

local v_lingan = fk.CreateTriggerSkill{
	name = "v_lingan",
	--默认播放配音，可以通过Mute=true关闭技能配音。
	mute = true,
	--赋予控制型技能定义
	anim_type = "control", 
	--时机：阶段开始时
	events = {fk.EventPhaseStart}, 
	--触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能.
	--					遍历到的角色处于结束阶段;
  --          存在可以被该技能选中的角色
	can_trigger = function(self, event, target, player, data)
    local room = player.room
    local v_trigger = false
    for _,p in ipairs(room:getOtherPlayers(player)) do
      if VslUtil.is_wounded(p) and VslUtil.SkillCanTarget(p, player, self.name) then
        v_trigger = true
      end
    end
		return target == player and player:hasSkill(self) 
      and player.phase == Player.Finish and v_trigger
	end,
	-- on_trigger = function(self, event, target, player, data)
	--   --if self:isEffectable(player) then
	--   self:doCost(event, target, player, data)
	--   --end
	-- end,
	on_cost = function(self, event, target, player, data)
		local room = player.room
    local targets = {}
    for _,p in ipairs(room:getOtherPlayers(player)) do
      if VslUtil.is_wounded(p) and VslUtil.SkillCanTarget(p, player, self.name) then
        table.insert(targets, p.id)
      end
    end
    if #targets > 0 then
      local tar = room:askForChoosePlayers(player, targets, 1, 1, "#v_lingan_ask", self.name, true)[1]
      --print(tar)
      if tar then
        local target = room:getPlayerById(tar)
        --只要黑色牌，这里之后注意一下
        self.cost_data = target
        return true
      end
    end
	end,
	on_use = function(self, event, target, player, data)
		local room = player.room
    local target = self.cost_data
    local card = room:askForCard(target, 1, 1, true, self.name, true, ".|.|spade,club","#v_lingan_give:"..player.id)[1]
    if card then
      --交牌
      room:moveCardTo(card, Player.Hand, player, fk.ReasonGive, self.name, nil, true)
    else
      room:setPlayerMark(target, "v_lingan_banned", 1)
      room:changeMaxHp(target, -1)
    end
	end,
}

--------------------------------------------------
--病院坂灵
--角色马克：
--------------------------------------------------

local bingyuanbanling_youlinfuling = General(extension, "bingyuanbanling_youlinfuling", "novus", 4, 4, General.Female)
bingyuanbanling_youlinfuling:addSkill(v_bingfu)
bingyuanbanling_youlinfuling:addSkill(v_lingan)

--------------------------------------------------
--占术
--------------------------------------------------

local v_zhanshu = fk.CreateTriggerSkill{
	name = "v_zhanshu",
	anim_type = "drawcard",
	events = {fk.AfterCardUseDeclared},
	can_trigger = function(self, event, target, player, data)
		return target == player and player:hasSkill(self) 
		and data.card and data.card.type == Card.TypeTrick
	end,
  on_cost = function(self, event, target, player, data)
    --确认是否发动技能。
    local room = player.room
    if room:askForSkillInvoke(player, self.name, data) then
      return true
    end
  end,
	on_use = function(self, event, target, player, data)
		local room = player.room
		if #player:getPile("v_zhanshu_pile")<=0 then
      local card_ids = room:getNCards(5)
      local to_return = table.random(card_ids, 1)
      local choice = "confirm"
      local get, top
      local result = room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseCardsAndChoiceBox.qml", {
        card_ids,
        {"confirm"},
        "#v_zhanshu_select",
        {},
        1,
        1,
      })
      if result ~= "" then
        local reply = json.decode(result)
        to_return = reply.cards
        choice = reply.choice
      end
      if to_return[1] and to_return[1] ~= -1 then
        local redCards,blackCards = {},{}

        for i = #card_ids, 1, -1 do
          local id = card_ids[i]
          if Fk:getCardById(id).color == Card.Black then
            table.insert(blackCards, id)
          elseif Fk:getCardById(id).color == Card.Red then
            table.insert(redCards, id)  
          end
          table.removeOne(card_ids, id)
        end
        if Fk:getCardById(to_return[1]).color == Card.Red then
          get = redCards
          top = blackCards
        elseif Fk:getCardById(to_return[1]).color == Card.Black then
          get = blackCards
          top = redCards
        end
      end
      if #get > 0 then
        for i = 1, #get do
          room:setCardMark(Fk:getCardById(get[i]), "@@v_zhanshu_inpile-cm!ldc*", 1)
        end
        player:addToPile("v_zhanshu_pile", get, true, self.name)
      end
      if #top > 0 then
        local cids = room:askForGuanxing(player, top, nil, {0,0}, self.name)
      end

      -- room:moveCards({
      --   ids = card_ids,
      --   toArea = Card.Processing,
      --   moveReason = fk.ReasonPut,
      -- })

		else
		  local cids = room:askForCard(player, 1, 1, false, self.name , false, 
		    ".|.|.|v_zhanshu_pile","v_zhanshu-ask2","v_zhanshu_pile" )
      if #cids > 0 then
        room:obtainCard(player.id, cids[1])
        room:setCardMark(Fk:getCardById(cids[1]), "@@v_zhanshu_inpile-cm!ldc*", 0)
      end
		end 
	end,
}

--------------------------------------------------
--通感
--------------------------------------------------

local v_tonggan = fk.CreateTriggerSkill{
  name = "v_tonggan",
  anim_type = "control",
  expand_pile = "v_zhanshu_pile",
  events = {fk.AskForRetrial},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and #player:getPile("v_zhanshu_pile") > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local card = room:askForCard(player, 1, 1, false, self.name, true, ".|.|.|v_zhanshu_pile|.|.", "#v_tonggan-choose", "v_zhanshu_pile")
    if #card > 0 then
      self.cost_data = card[1]
    return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player.room:retrial(Fk:getCardById(self.cost_data), player, data, self.name)
    room:setCardMark(Fk:getCardById(self.cost_data), "@@v_zhanshu_inpile-cm!ldc*", 0)
  end,

  refresh_events = {fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    local room = player.room
    local tonggan = false
    if room:getTag("FirstRound") then return false end
    for _, move in ipairs(data) do
      if move.from and move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          local c = Fk:getCardById(info.cardId, true)
          if c:getMark("@@v_zhanshu_inpile-cm!ldc*") > 0 then
            tonggan = true
          end
        end
        if tonggan and #player:getPile("v_zhanshu_pile") == 0 and player:isWounded() then
          return true
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:recover({
      who = player,
      num = 1,
      recoverBy = player,
      skillName = self.name
    })
    player.room:doAnimate("InvokeSkill", {
      name = "v_tonggan",
      player = player.id,
      skill_type = "support",
    })
  end,
}

--------------------------------------------------
--安晚
--------------------------------------------------

local anwan_yingganlingxin = General(extension, "anwan_yingganlingxin", "novus", 3, 3, General.Female)
anwan_yingganlingxin:addSkill(v_zhanshu)
anwan_yingganlingxin:addSkill(v_tonggan)

--------------------------------------------------
--化武
--------------------------------------------------

local v_huawu = fk.CreateTriggerSkill{
  name = "v_huawu",
  anim_type = "support",
  events = {fk.EventPhaseStart, fk.EventPhaseEnd},
  --使用条件：（已完成）
  --通用：
  -- 触发时机的角色为遍历到的角色、遍历到的角色具有本技能。
  -- 遍历到的角色处于出牌阶段。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
      and player.phase == Player.Play
  end,
  --使用询问：（已完成）
  --阶段开始时：
  -- 如技能未被元初类技能失效，询问是否发动技能。
  --阶段结束时：
  -- return true
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      if room:askForSkillInvoke(player, self.name, data) then
        return true
      end
    else
      return true
    end
  end,
  --使用流程：（未完成）
  --阶段开始时：
  -- 检索牌堆。
  -- 如果是装备牌且玩家可以使用这张牌（可以使用prohibituse检查），检查牌对应的装备区，如可用，纳入表中。
  -- 如装备表非空，从中提取最多三件装备。（提取后需要从原表删除装备）
  -- 如果提取表非空，生成AG选择装备，然后使用对应的装备并生成mark（暂定phase后清洗）
  --阶段结束时：
  -- 根据角色mark对应的ID数字，检查装备区的牌，如果存在相同ID的牌，则将其返回牌堆。
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local room = player.room
      --记录牌堆的装备牌。
      local equips = {}
      --这里没摸到牌堆/弃牌堆的牌
      local draw = room.draw_pile
      for _,p in ipairs(draw) do
        local card = Fk:getCardById(p)
        --（后续可以补充isavailable判定确保这个装备是可以被玩家装备的，如果出现玩家因为无法使用或装备区封印穿不上去的情况可以噶了。)
        if card.type == Card.TypeEquip and (not (not player:canUse(card) or player:prohibitUse(card))) then
          table.insert(equips, p)
        end
      end
      if #equips > 0 then
        local ag_equip = {}
        for i = 1, math.min(#equips, 3), 1 do
          local random_one = table.random(equips)
          table.insert(ag_equip, random_one)
          table.removeOne(equips, random_one)
        end
        if #ag_equip > 0 then
          room:fillAG(player, ag_equip)
          local id = room:askForAG(player, ag_equip, false, self.name)
          room:closeAG(player)
          local card = Fk:getCardById(id)
          if card then
            local new_use = {} ---@type CardUseStruct
            new_use.from = player.id
            --技能马克：可能会存在类似于知更酱多目标BUG的问题
            new_use.tos = {{ player.id }}
            new_use.card = card
            new_use.skillName = self.name
            --测试skillName是否有效
            --print(new_use.skillName)
            room:useCard(new_use)
            room:setPlayerMark(player, self.name, id)
          end
        end
      end
    -- 根据角色mark对应的ID数字，检查装备区的牌，如果存在相同ID的牌，则将其返回牌堆。
    else
      local mar = player:getMark(self.name)
      local equ = player:getCardIds(Player.Equip)
      if #equ > 0 then
        for _,cid in ipairs(equ) do
          if cid == mar then
            VslUtil.return_draw_pile(player, {mar}, self.name)
            -- local ram = math.random(1, #room.draw_pile + 1)
            -- room:moveCards({
            --   ids = {mar},
            --   from = player.id,
            --   toArea = Card.DrawPile,
            --   moveReason = fk.ReasonJustMove,
            --   skillName = self.name,
            --   drawPilePosition = ram,
            -- })
          end
        end
      end
      room:setPlayerMark(player, self.name, 0)
    end
  end,
}

--------------------------------------------------
--三叹
--TODO:如果选择用全局标记，需要确认这个技能会不会在三叹触发锦囊牌的时候
--       被无懈可击干扰技能发动（变成无懈可击触发三叹就搞笑了）
--     data.card:geteffectiveid()会拿到第一张真实牌···虚拟牌怎么整是个问题
--FIXME:草 这个时机是失败的，根本没问无懈！！！！
--------------------------------------------------

--这是旧版（强力版），先凑活着用吧兄弟们。
local v_santan = fk.CreateTriggerSkill{
  name = "v_santan",
  --赋予输出型技能定义,
  anim_type = "offensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：卡牌生效前/目标指定后（看注释掉哪个就行）
  --注释：被无懈后依然能进入“卡牌生效前”流程
  --注释2：如想要实现未削弱版效果，只能通过“卡牌生效前”时机
  --注释3：“目标指定后”对无懈可击/闪这种不指定目标的牌无效，虽然可以变相实现现版本效果，但没必要（从log上来看不算完美实现）。
  events = {fk.PreCardEffect},
  -- events = {fk.TargetSpecified},
  --使用条件：
  --             触发时机的角色为遍历到的角色，遍历到的角色拥有此技能，
  --             遍历到的角色的某个标记符合要求，
  --             本次流程中第一次触发这个时机
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) 
    and player:getMark("@v_santan_mark") == "O"
    -- and data.firstTarget
  end,
  --使用流程：
  --令这张牌不可被响应。
  on_use = function(self, event, target, player, data)
    local room = player.room
    if not data.card:isVirtual() then
      room:sendLog{
        type = "#v_santan_triggered",
        from = player.id,
        arg = self.name,
        card = { data.card.id },
      }
    else
      room:sendLog{
        type = "#v_santan_virtual_triggered",
        from = player.id,
        arg = self.name,
        arg2 = data.card:toLogString(),
      }
    end
    data.disresponsive = true
  end,

  --本刷新仅用于在牌使用完毕后根据牌使用次数刷新BUFF
  --时机：手牌使用声明后
  refresh_events = {fk.AfterCardUseDeclared},
  --刷新条件：
  --             触发时机的角色为遍历到的角色，遍历到的角色拥有此技能，
  --             遍历到的角色的某个标记符合要求，
  --             本次流程中第一次触发这个时机（先删了）
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  --刷新方式：待定
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local v_stm = (player:getMark("card_used") + 1) % 3
    room:setPlayerMark(player, "@v_santan_mark", v_stm)
    if v_stm == 0 then
      room:setPlayerMark(player, "@v_santan_mark", "O")
    end
  end
}

-- 这也没用，规避无懈无效不说，on_use注释部分还有个莫名其妙的nil，先做个旧版的吧。
-- local v_santan = fk.CreateTriggerSkill{
--   name = "v_santan",
--   --赋予输出型技能定义,
--   anim_type = "offensive",
--   --技能为锁定技，满足条件后强制发动
--   frequency = Skill.Compulsory,
--   --时机：卡牌生效前
--   --注释：被无懈后依然能进入“卡牌生效前”流程
--   -- events = {fk.PreCardEffect},
--   events = {fk.TargetSpecified},
--   --使用条件：
--   --             触发时机的角色为遍历到的角色，遍历到的角色拥有此技能，
--   --             遍历到的角色的某个标记符合要求，
--   --             本次流程中第一次触发这个时机
--   can_trigger = function(self, event, target, player, data)
--     return target == player and player:hasSkill(self) 
--     and player:getMark("@v_santan_mark") == "O"
--     -- 下面这行本来是想用来规避无懈的，结果好像没什么用.zip
--     and not (Fk.currentResponsePattern and Fk.currentResponsePattern == "nullification")
--     -- and player:getMark("card_used") % 3 == 2
--     and data.firstTarget
--   end,
--   --使用流程：
--   --令这张牌不可被响应。
--   on_use = function(self, event, target, player, data)
--     local room = player.room
--     room:sendLog{
--       type = "#v_santan_triggered",
--       from = player.id,
--       arg = self.name,
--       card = { data.card.id },
--     }
--     local tar = AimGroup:getAllTargets(data.tos)
--     if #tar > 0 then
--       for _, p in ipairs(tar) do
--         -- local pls = room:getPlayerById(p)

--         data.disresponsiveList = data.disresponsiveList or {}
--         if #data.disresponsiveList == 0 then
--           table.insert(data.disresponsiveList, p)
--         end
--         --因为这部分内容的存在，导致了attempt to get length of a nil value(local 'self')
--         --util.lua:88 table.contains
--         --room.lua:1995 doCardUseEffect
--         --usecard.lua:197···
--         table.insertIfNeed(data.disresponsiveList, p)
--       end
--     end
--     -- data.disresponsive = true
--   end,

--   --本刷新仅用于在牌使用完毕后根据牌使用次数刷新BUFF
--   --时机：手牌使用声明后
--   refresh_events = {fk.AfterCardUseDeclared},
--   --刷新条件：
--   --             触发时机的角色为遍历到的角色，遍历到的角色拥有此技能，
--   --             遍历到的角色的某个标记符合要求，
--   --             本次流程中第一次触发这个时机（先删了）
--   can_refresh = function(self, event, target, player, data)
--     return target == player and player:hasSkill(self)
--     -- return data.firstTarget
--   end,
--   --刷新方式：待定
--   on_refresh = function(self, event, target, player, data)
--     local room = player.room
--     local v_stm = (player:getMark("card_used") + 1) % 3
--     room:setPlayerMark(player, "@v_santan_mark", v_stm)
--     if v_stm == 0 then
--       room:setPlayerMark(player, "@v_santan_mark", "O")
--     end
--   end
-- }

--------------------------------------------------
--希贝尔
--------------------------------------------------

local xibeier_sanjueweibian = General(extension, "xibeier_sanjueweibian", "facemoe", 4, 4, General.Female)
xibeier_sanjueweibian:addSkill(v_huawu)
xibeier_sanjueweibian:addSkill(v_santan)
-- xibeier_sanjueweibian:addSkill(v_cheat)

--------------------------------------------------
--低吟
--------------------------------------------------

local v_diyin = fk.CreateViewAsSkill{
  name = "v_diyin",
  interaction = UI.ComboBox {choices = VslUtil.damage_tricks},
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = function()
    return false
  end,
  view_as = function(self, cards)
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcards(Self:getCardIds(Player.Hand))
    card.skillName = self.name
    return card
  end,
}
local v_diyin_draw = fk.CreateTriggerSkill{
  name = "#v_diyin_draw",
  --赋予输出型技能定义
  anim_type = "offensive",
  --时机：手牌结算后
  events = {fk.CardUseFinished},
  --触发条件：
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
    and data.card and data.card.skillName == "v_diyin"
    -- and data.card and table.contains(data.card.skillNames, "v_diyin")
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local pla = room:getPlayerById(data.from)
    if pla and pla:isAlive() then
      room:drawCards(pla, 1, "v_diyin")
    end
    for _, p in ipairs(room:getAllPlayers()) do
      if p:getMark("v_diyin_damage-phase") > 0 then
        room:setPlayerMark(p, "v_diyin_damage-phase", 0)
        --之后能否被技能指定为目标可以在这判定
        room:drawCards(p, 1, "v_diyin")
      end
    end
  end,

  --刷新时机：受到伤害后
  refresh_events = {fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    return data.card and data.card.skillName == "v_diyin" 
    -- return data.card and table.contains(data.card.skillNames, "v_diyin")
    and data.to and data.to:isAlive()
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(data.to, "v_diyin_damage-phase", 1)
  end
}
v_diyin:addRelatedSkill(v_diyin_draw)


--------------------------------------------------
--库姬
--角色马克：
--------------------------------------------------

local kuji_chaoyongyuge = General(extension, "kuji_chaoyongyuge", "facemoe", 4, 4, General.Female)
kuji_chaoyongyuge:addSkill(v_diyin)

--------------------------------------------------
--矛盾
--技能马克：
--------------------------------------------------

local v_maodun = fk.CreateTriggerSkill{
  --（刚需）技能认证名
  name = "v_maodun",
  --(非必要）赋予进攻型技能定义
  anim_type = "offensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：受到伤害时，造成伤害时
  events = {fk.DamageInflicted,fk.DamageCaused},
  --触发条件：
  --触发时机的角色为遍历到的角色、遍历到的角色具有本技能、造成的伤害大于0；
  --遍历到的角色体力值为全场唯一最高。
  --（后续补充）非光伤
  can_trigger = function(self, event, target, player, data)
    if not (target == player and player:hasSkill(self) and
      data.damage > 0) then 
      return false 
    end
    local room = player.room
    local others = room:getOtherPlayers(player)
    for _,p in ipairs(others) do
      if p.hp >= player.hp then
        return false
      end
    end
    return true
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage + 1
  end,
}

--------------------------------------------------
--制冷
--获取寒冰剑部分原Vup杀流程：
--奇数回合准备阶段，将一张寒冰剑放置于除外牌堆里，进行选择：
--如不用，置于某个未知牌堆
--如用，直接使用（参考成长）

--TODO:装备区是否封印的检测；
--  为优化体验避免没剑还询问技能，把检测放到了can_trigger；如对游戏体验变化太大可修改回on_cost。
--------------------------------------------------

local v_zhileng = fk.CreateTriggerSkill{
  name = "v_zhileng",
  anim_type = "defensive",
  events = {fk.EventPhaseStart, fk.DamageInflicted},
  --触发条件：（已完成）
  --通用：
  -- 触发时机的角色为遍历到的角色、遍历到的角色具有本技能。
  --阶段开始时：【可以考虑在这里做个装备区是否有寒冰剑的判定】
  -- 游戏轮数为奇数；遍历到的角色处于准备阶段。
  -- （武器存在且为寒冰剑）这项不为真
  --受到伤害时：
  -- 伤害大于0，遍历到的角色牌区牌>=2
  -- （待补充）非光伤
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if target ~= player or not player:hasSkill(self) then return false end
    if event == fk.EventPhaseStart then
      local weapon1 = player:getEquipment(Card.SubtypeWeapon) 
      return room:getTag("RoundCount") % 2 == 1 and player.phase == Player.Start
        and not (weapon1 and Fk:getCardById(weapon1).name == "ice_sword")
    else
      return data.damage > 0 and #player:getCardIds{Player.Hand, Player.Equip} >= 2
    end
  end,
  --使用询问：
  --阶段开始时：
  -- 在牌堆和弃牌堆找寒冰剑。（寻找判定中需要注意后续补充装备区是否被废除或无法使用）
  -- 如找到，放置于除外区，并确认玩家可以使用这张牌（可以通过prohibituse来）后询问技能是否发动
  --受到伤害时：
  -- askfordiscard即可，2牌，带装备玩。
  on_cost = function(self, event, target, player, data)
    local room = player.room
    --确认是否使用寒冰剑，否则就把寒冰剑返回牌堆。
    if event == fk.EventPhaseStart then
      --记录牌堆及弃牌堆的寒冰剑。
      local equips = {}
      --这里没摸到牌堆/弃牌堆的牌
      local draw = room.draw_pile
      local discard = room.discard_pile
      for _,p in ipairs(draw) do
        local card = Fk:getCardById(p)
        --（后续可以补充isavailable判定确保这个装备是可以被玩家装备的，如果出现玩家因为装备区废除穿不上去的情况可以噶了。)
        if card and card.name == "ice_sword" then
          table.insert(equips, p)
        end
      end
      for _,p in ipairs(discard) do
        local card = Fk:getCardById(p)
        --（后续可以补充isavailable判定确保这个装备是可以被玩家装备的，如果出现玩家因为装备区废除穿不上去的情况可以噶了。)
        if card and card.name == "ice_sword" then
          table.insert(equips, p)
        end
      end
      if #(equips) > 0 then
        local x = #(equips)
        local c = math.random(1, x)
        local carcar = equips[c]
        local carcarcar = Fk:getCardById(carcar)
        local prompt = "v_zhileng_ask2:::"..carcarcar.name
        player:addToPile(self.name, carcarcar, true, self.name)
        if (not (not player:canUse(carcarcar) or player:prohibitUse(carcarcar))) then
          local car = room:askForSkillInvoke(player, self.name, data, prompt)
          if car then
            self.cost_data = carcar
            return true
          else
            VslUtil.return_draw_pile(player, {carcar}, self.name)
            -- local ram = math.random(1, #room.draw_pile + 1)
            -- room:moveCards({
            --   ids = {carcar},
            --   from = player.id,
            --   toArea = Card.DrawPile,
            --   moveReason = fk.ReasonJustMove,
            --   skillName = self.name,
            --   drawPilePosition = ram,
            -- })
          end
        end
      end
    --选择弃牌与否
    else
      local prompt = "v_zhileng_ask1"
      local disc = room:askForDiscard(player, 2, 2, true, self.name, true, ".", prompt)
      return #disc == 2
    end
  end,
  --使用流程：
  --阶段开始时：
  -- 如确定使用，直接用；如不用，返回牌堆。
  --受到伤害时：
  --setemotion后，return true
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      local is = self.cost_data
      local icesword = Fk:getCardById(is)
      local new_use = {} ---@type CardUseStruct
      new_use.from = player.id
      --技能马克：可能会存在类似于知更酱多目标BUG的问题
      new_use.tos = {{ player.id }}
      new_use.card = icesword
      new_use.skillName = self.name
      --测试skillName是否有效
      --print(new_use.skillName)
      room:useCard(new_use)
    else
      local address = "./packages/"..VslUtil.extensionName.."/image/anim/jiuma_small"
      room:setEmotion(player, address)
      return true
    end
  end,
}

--------------------------------------------------
--玖麻
--------------------------------------------------

local jiuma_hanshixianggong = General(extension, "jiuma_hanshixianggong", "facemoe", 4, 5, General.Female)
jiuma_hanshixianggong:addSkill(v_maodun)
jiuma_hanshixianggong:addSkill(v_zhileng)

--------------------------------------------------
--联袂
--技能马克：
--------------------------------------------------

local v_lianmei = fk.CreateTriggerSkill{
  name = "v_lianmei",
  --赋予控场型技能定义
  anim_type = "control",
  --时机：受到伤害后
  events = {fk.Damaged},
  --触发条件：
  -- 触发时机的角色为遍历到的角色；遍历到的角色具有本技能；
  -- 伤害大于0，存在伤害源
  can_trigger = function(self, event, target, player, data)
    local damage = data
    return target == player and player:hasSkill(self) 
    and damage.damage > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local prompt = "#v_lianmei_ask"
    local alive = room:getAlivePlayers()
    local targets = {}
    for _,p in ipairs(alive) do
      -- TODO：这里后续可以补充“可被技能指定”与“你的技能可以对其生效”判定，待定
      if (not p:isNude()) then
        table.insert(targets, p.id)
      end
    end
    local ret = room:askForChoosePlayers(player, targets, 1, 1, prompt, self.name, true)
    if #ret > 0 then
      self.cost_data = ret[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(self.cost_data)
    if not tar:isNude() then
      room:askForDiscard(tar, 1, 1, true, self.name, false)
    end
    --这里可以补一个玩家能否弃置对方一张牌
    if not tar:isNude() then
      local card = room:askForCardChosen(player, tar, "he", self.name)
      room:throwCard(card, self.name, tar, player)
    end
  end,
}

--------------------------------------------------
--小希小桃
--角色马克：
--------------------------------------------------

local xiaoxixiaotao_eniac = General(extension, "xiaoxixiaotao_eniac", "xuyanshe", 4, 4, General.Female)
xiaoxixiaotao_eniac:addSkill(v_lianmei)

--------------------------------------------------
--龙息
--------------------------------------------------

local v_longxi = fk.CreateTriggerSkill{
  name = "v_longxi",
  --赋予输出型技能定义,
  anim_type = "offensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified},
  --触发条件：触发时机的角色为遍历到的角色，触发者拥有此技能，
  --             触发者本回合已使用过一张牌，触发者处于出牌阶段，
  --             本次流程中第一次触发这个时机
  can_trigger = function(self, event, target, player, data)
    local targets = data
    return target == player and player:hasSkill(self) 
    and player.phase == Player.Play and player:getMark("#v_longxi_mark-turn") == 1
    and targets.firstTarget
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = data
    local longxi_tar = AimGroup:getAllTargets(targets.tos)
    --选择这张牌指定的所有目标，执行拆一张牌的指令
    for _, p in ipairs(longxi_tar) do
      local pls = room:getPlayerById(p)
      --如果被选定的目标两个区域都没牌则不执行下一步。
      if (not pls:isNude()) then
        --由遍历到的角色对目标选择手牌区/装备区的一张牌
        local cid = room:askForCardChosen(
          player,
          pls,
          "he",
          self.name
        )
        --将这张牌丢弃牌区
        room:throwCard(cid, self.name, pls, player)
      end
    end
  end,
  refresh_events = {fk.TargetSpecified},
  can_refresh = function(self, event, target, player, data)
    local targets = data
    if not (target == player and player:hasSkill(self)) then
      return false
    end
    return player.phase == Player.Play and targets.firstTarget
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:addPlayerMark(player,"#v_longxi_mark-turn", 1)
  end
}

--------------------------------------------------
--卡诺娅
--角色马克：
--------------------------------------------------

local kanuoya_akanluerbanlong = General(extension, "kanuoya_akanluerbanlong", "xuyanshe", 4, 4, General.Female)
kanuoya_akanluerbanlong:addSkill(v_longxi)

--------------------------------------------------
--离鸢
--------------------------------------------------

--------------------------------------------------
--不倦
--可以考虑为了这个技能做一个在特定时机可以更新的标记用来记录和不同角色的距离
--------------------------------------------------

--------------------------------------------------
--新黎歌
--角色马克：
--------------------------------------------------

-- local lige_jiuyixinsheng = General(extension, "lige_jiuyixinsheng", "xuyanshe", 3, 3, General.Female)
-- lige_jiuyixinsheng:addSkill(v_liyuan)
-- lige_jiuyixinsheng:addSkill(v_bujuan)

--------------------------------------------------
--狐尾扇
--技能马克：后续可以给展示用的牌做cardflag
--------------------------------------------------

local v_huweishan_prohibit = fk.CreateProhibitSkill{
  name = "#v_huweishan_prohibit",
  prohibit_use = function(self, player, card)
    if card and card:getMark("v_huweishan-turn") > 0 and player:getMark("v_huweishan-turn") > 0 then
      return true
    end
  end,
}


local v_huweishan = fk.CreateTriggerSkill{
  name = "v_huweishan",
  --赋予输出型技能定义
  anim_type = "offensive",
  -- --时机：手牌结算后
  -- events = {fk.CardUseFinished},
  --时机：宣告手牌使用时
  events = {fk.AfterCardUseDeclared},
  --（阶段变化时）触发时机的角色为遍历到的角色；遍历到的角色具有本技能；存在实体卡（后续需要测试，如不成功可以通过ID>0处理）。
  --             使用的牌为杀；本回合只使用过一次技能。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card
    and data.card.trueName == "slash" and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card_id = room:drawCards(player, 1, self.name, top)[1]
    local card = Fk:getCardById(card_id)
    room:obtainCard(player, card_id, true, fk.ReasonDraw)
    room:delay(250)
    if room:getCardOwner(card_id) == player then
      player:showCards(card)
      if card.type == Card.TypeBasic then
        local prompt = "v_huweishan_throw_choice"
        if VslUtil.yes_or_no(player, self.name, prompt) then
          local address = "./packages/"..VslUtil.extensionName.."/image/anim/xingmengzhenxue"
          room:setEmotion(player, address)
          -- room:throwCard(card_id, self.name, player, player)
          player:addCardUseHistory(data.card.trueName, -1)

          --注释：发log用的to是一维数组，而tos是二维数组
          if not data.card:isVirtual() then
            room:sendLog{
              type = "#v_huweishan_success",
              from = player.id,
              arg = self.name,
              card = { data.card.id },
            }
          elseif data.card:isVirtual() then
            room:sendLog{
              type = "#v_huweishan_success_virtual",
              from = player.id,
              arg = self.name,
              arg2 = data.card:toLogString(),
            }
          end
          room:addPlayerMark(player, "v_huweishan-turn", 1)
          room:addCardMark(card, "v_huweishan-turn", 1)
        end
      end
    end
  end,
}
v_huweishan:addRelatedSkill(v_huweishan_prohibit)

--------------------------------------------------
--星梦真雪
--------------------------------------------------

local xingmengzhenxue_rongyixiaohu = General(extension,"xingmengzhenxue_rongyixiaohu", "niya", 4, 4, General.Bigender)
xingmengzhenxue_rongyixiaohu:addSkill(v_huweishan)

--------------------------------------------------
--无忌
--技能马克：刷新标记暂时就不放在refresh_event了，我也不确定优先级（呆滞）
--------------------------------------------------

--写完才发现好像完全没必要再写个function（乐）
--虽然超大规模降低了可读性，但我懒得改了~
local function refresh_wuji_buding_mark(player, suit)
  local record_suits = player:getMark("v_wuji_record")
  local room = player.room
  local suit_s = {}
  --存在0个花色：直接为record_suit赋予suit变量。
  if record_suits == 0 then
    record_suits = suit
  --存在>=一个花色：提取现有花色增加目标花色后，
  --  将其按照suits表的顺序进行比较并 依次 放入表内。
  elseif type(record_suits) == "string" then
    suit_s = record_suits:split("+")
    table.insertIfNeed(suit_s, suit)
    local show_suit = {}
    for _,s in ipairs(VslUtil.suits) do
      if table.contains(suit_s, s) then
        table.insertIfNeed(show_suit, s)
      end
    end
    record_suits = table.concat(show_suit, "+")
  end
  --设置对应的标记。
  room:setPlayerMark(player, "v_wuji_record", record_suits)
	room:setPlayerMark(player, "@v_wuji_suit", table.concat(
    table.map(record_suits:split("+"), function(s) return VslUtil.card_suits_table[s] end)
    , ""))
  return #suit_s
end
local v_wuji = fk.CreateTriggerSkill{
  name = "v_wuji",
  --赋予特殊型技能定义
  anim_type = "special",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --启动后不默认播放技能触发
  mute = true,
  --时机：手牌结算后
  events = {fk.CardUseFinished},
  --触发条件：
  --触发时机的角色为遍历到的角色、遍历到的角色存在此技能；
  --存在花色且不为无色；
  --本花色未被记录过。
  can_trigger = function(self, event, target, player, data)
    local record_suits = player:getMark("v_wuji_record")
    local suit_s = {}
    local su_st = VslUtil.suit_string(data.card.suit)
    local record = false
    if type(record_suits) == "string" then
      suit_s = record_suits:split("+")
      for _,s in ipairs(suit_s) do
        if su_st == s then
          record = true
          break
        end
      end
    end
    return target == player and player:hasSkill(self) 
      and data.card.suit and data.card.suit ~= Card.NoSuit
      and (not record)
  end,
  on_use = function(self, event, target, player, data)
    --遍历全场所有角色，对持有此技能的角色询问其是否发动技能。
    local room = player.room
    local su_st = VslUtil.suit_string(data.card.suit)
    local count
    count = refresh_wuji_buding_mark(player, su_st)
    if count == 3 then
      room:notifySkillInvoked(player, self.name)
      player:broadcastSkillInvoke(self.name, -1)
      room:drawCards(player, 1, self.name)
    elseif count == 4 then
      room:notifySkillInvoked(player, self.name)
      player:broadcastSkillInvoke(self.name, -1)
      room:setPlayerMark(player, "v_wuji_record", 0)
      room:setPlayerMark(player, "@v_wuji_suit", 0)
      local alives = room:getAlivePlayers()
      local prompt = "v_wuji_ask"
      local targets = {}
      for _, p in ipairs(alives) do
        table.insert(targets, p.id)
      end
      if #targets > 0 then
        local tar = room:askForChoosePlayers(player, targets, 1, 1, prompt, self.name, true)[1]
        if tar then
          local ta = room:getPlayerById(tar)
          if ta ~= player then
            --doindicate的两个参数一个为integer，一个为table
            room:doIndicate(player.id, { tar })
          end
          room:damage{
            from = player,
            to = ta,
            damage = 1,
            skillName = self.name,
          }
        end
      end
    end
  end,
}

--------------------------------------------------
--幼步玎
--------------------------------------------------

local buding_lichilingya = General(extension, "buding_lichilingya", "niya", 3, 3, General.Female)
buding_lichilingya:addSkill(v_wuji)

--------------------------------------------------
--消忧
--------------------------------------------------

local v_xiaoyou = fk.CreateTriggerSkill{
  name = "v_xiaoyou",
  --赋予控场型技能定义
  anim_type = "control",
  --时机：阶段开始时
  events = {fk.EventPhaseStart},
  --触发条件：
  can_trigger = function(self, event, target, player, data)
    local ret = player:hasSkill(self) and player ~= target
      and target:isAlive() and target.phase == Player.Start
      and not target:isNude() 
      and target:canUse(Fk:cloneCard("analeptic")) and not target:prohibitUse(Fk:cloneCard("analeptic"))
    if ret then
      --确认是否存在不为酒的牌。
      local allcards = {}
      local new_cards = {}
      table.insertTable(allcards, target:getCardIds(Player.Hand))
      table.insertTable(allcards, target:getCardIds(Player.Equip))
      local ids = table.filter(allcards, function(id)
        return Fk:getCardById(id).name ~= "analeptic"
      end)
      if #ids > 0 then
        return true
      end
    end
    return false
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if room:askForSkillInvoke(player, self.name, data, "v_xiaoyou_choice:"..target.id) then
      if player ~= target then
        --doindicate的两个参数均为integer类型，一般为角色id
        room:doIndicate(player.id, { target.id })
      end
      -- room:setEmotion(player, "./packages/vupslash/image/skill/mengcike"..math.random(1,2))
      local address = "./packages/"..VslUtil.extensionName.."/image/skill/mengcike1"
      room:setEmotion(player, address)
      --确认是否存在不为酒的牌。
      local allcards = {}
      local new_cards = {}
      table.insertTable(allcards, target:getCardIds(Player.Hand))
      table.insertTable(allcards, target:getCardIds(Player.Equip))
      local ids = table.filter(allcards, function(id)
        return Fk:getCardById(id).name ~= "analeptic"
      end)
      local card = room:askForCard(target, 1, 1, true, self.name, false, 
        tostring(Exppattern{ id = ids }), "@v_xiaoyou_use")
      if #card > 0 then
        self.cost_data = card[1]
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local car = Fk:getCardById(self.cost_data)
    local card = Fk:cloneCard("analeptic", Card.NoSuit, 0)
    card:addSubcard(car)
    card.skillName = self.name
    local new_use = {} ---@type CardUseStruct
    new_use.from = target.id
    --技能马克：可能会存在类似于知更酱多目标BUG的问题
    new_use.tos = { { target.id } }
    new_use.card = card
    room:useCard(new_use)
  end,
}

--------------------------------------------------
--识心
--------------------------------------------------

local v_shixin_m = fk.CreateActiveSkill{
  name = "v_shixin_m",
  anim_type = "control",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  target_num = 1,
  --card_num = 0,
  card_filter = function(self, to_select, selected, selected_targets)
    return false
  end,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    local player = Fk:currentRoom().current
    --可以在这里后续加caneffect
    return #selected == 0 and to_select ~= Self.id and (not target:isKongcheng())
      and VslUtil.SkillCanTarget(target, player, self.name)
  end,
  on_use = function(self, room, effect)
    --local players = room.players
    local from = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    --获取目标手牌并交给角色
    local cards = {}
    table.insertTable(cards, to:getCardIds(Player.Hand))
    local X = #cards
    if X > 0 then
      -- room:obtainCard(from, cards, false, self.name)
      room:moveCards( 
        {
          ids = cards,
          from = effect.tos[1],
          to = effect.from,
          fromArea = Card.PlayerHand,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonPrey,
          proposer = effect.from,
          skillName = self.name,
        }
      )
    end
    room:delay(500)
    local cards_giveback = room:askForCard(from, X, X, false, self.name, false, ".", "#v_shixin_m_give::"..effect.tos[1]..":"..X)
    if cards_giveback and #cards_giveback > 0 then
      room:moveCards( 
        {
          ids = cards_giveback,
          from = effect.from,
          to = effect.tos[1],
          fromArea = Card.PlayerHand,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonGive,
          proposer = effect.from,
          skillName = self.name,
        }
      )
    end
    if room:askForSkillInvoke(to, self.name, nil, "v_shixin_m_choice:"..effect.from) then
      room:doIndicate(effect.tos[1], { effect.from })
      local address = "./packages/"..VslUtil.extensionName.."/image/skill/mengcike3"
      room:setEmotion(from, address)
      room:loseHp(from, 1, self.name)
    end
  end,
}

--------------------------------------------------
--孟辞柯
--------------------------------------------------

local mengcike_zuishengmengsi = General(extension,"mengcike_zuishengmengsi", "bisonpro", 3, 3, General.Female)
mengcike_zuishengmengsi:addSkill(v_xiaoyou)
mengcike_zuishengmengsi:addSkill(v_shixin_m)

--------------------------------------------------
--蓁惹
--技能马克：作为目标疑似会导致雌雄双股剑无效。
--------------------------------------------------

local v_zhenre = fk.CreateTriggerSkill{
  name = "v_zhenre",
  --赋予防御型技能定义
  anim_type = "defensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：目标确定后
  events = {fk.TargetConfirmed},
  --触发条件：目标为玩家、玩家具有本技能、牌的种类为杀、牌的花色为红桃或黑桃。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      (data.card.trueName == "slash" and (data.card.suit == Card.Heart or data.card.suit == Card.Spade))
  end,
  on_use = function(self, event, target, player, data)
    table.insert(data.nullifiedTargets, player.id)
  end,
}

--------------------------------------------------
--芳仙
--技能马克：优化芳仙本体技能发动时的描述（可以考虑第一阶段的choice也做成锁定技，然后用askchooseplayer一类的方法插入tips）。
--------------------------------------------------

local v_fangxian_choice = fk.CreateTriggerSkill{
  name = "#v_fangxian_choice",
  --赋予支援型技能定义
  anim_type = "support",
  --时机：阶段变化时
  events = {fk.EventPhaseChanging},
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能，下一阶段为摸牌阶段，摸牌阶段未被跳过。
  can_trigger = function(self, event, target, player, data)
    local change = data
    --阶段变化时，实现“是否跳摸牌”的效果。 
    --exist_or_not：用来确认是否跳过对应阶段，类似于以前的Player:isSkipped()
    return target == player and player:hasSkill(self) 
    and change.to == Player.Draw and VslUtil.exist_or_not(player, Player.Draw)
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  -- on_cost = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   return true
  --   --end
  -- end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    --阶段变化时，实现“是否跳摸牌”的效果。
    local change = data
    if change.to == Player.Draw then
        --技能被无效化的效果试作
        --if self:isEffectable(player) then
        room:setPlayerMark(player, "@@v_fangxian-turn", 1)
        --end
        --此处不使用player:skip()而使用return true原因如下：
        --N神原话：触发技被触发的源头为Gamelogic::trigger（这个可以参考文档）
        --根据源码serverplay.lua中play函数的表示（其用于每个阶段的衍生），每个阶段开始时会先检索一次跳过阶段
        --由于其相关概念影响到触发时机，因此影响到了on_use中skip函数的使用
        --新版本说法：时机为change阶段时，跳阶段的检测已经完成，此时把下一个阶段塞进跳阶段列表里无效。
        return true
        --end
      --end
    end
  end,
}
local v_fangxian = fk.CreateTriggerSkill{
  name = "v_fangxian",
  --赋予支援型技能定义
  anim_type = "support",
  --时机：阶段开始时
  events = {fk.EventPhaseStart},
  --触发条件：遍历到的角色处于结束阶段，通过芳仙跳过摸牌阶段。
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if player.phase == Player.Finish and player:getMark("@@v_fangxian-turn") > 0 then
      --在场且存活
      --for _, p in ipairs(room:getAlivePlayers()) do
      return true
      --end
    end
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    --阶段变化时，实现“是否跳摸牌”的效果。
    if player.phase == Player.Finish and player:getMark("@@v_fangxian-turn") > 0 then
      --制作一个囊括所有存活角色的table-targets
      local alives = room:getAlivePlayers()
      local prompt = "#v_fangxian-target"
      local targets = {}
      for _, p in ipairs(alives) do
        table.insert(targets, p.id)
      end
      --to：从targets中选择1个目标，是个值为number的table。
      local to = room:askForChoosePlayers(player, targets, 1, 1, prompt, self.name)
      --这里后续可以增加“技能发动者是否可以对对应角色使用技能”的判定，类似于caneffect函数。
      if #to > 0 then
        --通过ID找到对应的ServerPlayer
        local player_to = room:getPlayerById(to[1])
        --指向类特效用函数doIndicate，但执行后由于不明原因在367行报了function的错，不理解。
        --room:doAnimate(1, player:objectName(), to:objectName()) --doAnimate 1:产生一条从前者到后者的指示线
        if player_to ~= player then
          --doindicate的两个参数均为integer类型，一般为角色id
          room:doIndicate(player.id, to)
        end
        room:recover{
          who = player_to,
          num = 1,
          recoverBy = player,
          skillName = self.name
        }
      else
        player:drawCards(2, self.name)
      end
    end
  end,

  --目前萌以前写的标记一键删除姬还没做出来，因此还是用比较原始的refresh处理。
  -- refresh_events = {fk.EventPhaseStart},
  -- can_refresh = function(self, event, target, player, data)
  --   if not (target == player and player:hasSkill(self)) then
  --     return false
  --   end
  --   if event == fk.EventPhaseStart then
  --     return player.phase == Player.NotActive
  --   end
  -- end,
  -- on_refresh = function(self, event, target, player, data)
  --   local room = player.room
  --   room:setPlayerMark(player, "@@v_fangxian-turn", 0)
  -- end
}

-- table.insert(turn_end_clear_mark, "@@v_fangxian-turn")

v_fangxian:addRelatedSkill(v_fangxian_choice)

--------------------------------------------------
--桃水纪
--角色马克：蓁惹，芳仙
--------------------------------------------------

local taoshuiji_fenhuafutao = General(extension, "taoshuiji_fenhuafutao", "individual", 4, 4, General.Female)
taoshuiji_fenhuafutao:addSkill(v_zhenre)
taoshuiji_fenhuafutao:addSkill(v_fangxian)

--------------------------------------------------
--视幻
--------------------------------------------------

local v_shihuan_buff =  fk.CreateMaxCardsSkill{
  name = "#v_shihuan_buff",
  fixed_func = function(self, player)
    if player:getMark("@v_shihuan_card-turn") > 0 then
      return player:getMark("@v_shihuan_card-turn")
    end
  end
}
local v_shihuan = fk.CreateTriggerSkill{
  name = "v_shihuan",
  --赋予控场型技能定义
  anim_type = "control",
  --时机：阶段开始时
  events = {fk.EventPhaseStart},
  --触发条件：遍历到的角色处于准备阶段；遍历全场所有角色，存在角色持有该技能。
  can_trigger = function(self, event, target, player, data)
    return target.phase == Player.Start
    and player:hasSkill(self) and player:usedSkillTimes(self.name, Player.HistoryRound) < 1
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local prompt = "v_shihuan_choice:"..target.id.."::"..target:getHandcardNum()
    if room:askForSkillInvoke(player, self.name, data, prompt) then
      return true
    end
    --   end
    -- end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if target ~= player then
      --doindicate的两个参数一个为integer，一个为table
      room:doIndicate(player.id, { target.id })
    end
    -- TODO:后续这里做log在提示信息中说明角色手牌上限调整。
    room:sendLog{
      type = "#v_shihuan_log",
      to = {target.id},
      arg = self.name,
      arg2 = math.max(1, target:getHandcardNum()),
    }
    room:setPlayerMark(target, "@v_shihuan_card-turn", math.max(1, target:getHandcardNum()))
    room:setPlayerMark(player, "@@v_shihuan_used-round", 1)
  end,
}

v_shihuan:addRelatedSkill(v_shihuan_buff)

--------------------------------------------------
--可餐
--TODO：锦囊牌显示好结果暂时无法出现，有概率要把所有牌的名字写上去。
--------------------------------------------------

local v_kecan = fk.CreateTriggerSkill{
  name = "v_kecan",
  --赋予负面型技能定义
  anim_type = "negative",
  --时机：受到伤害后
  events = {fk.Damaged},
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能，伤害大于0，存在伤害来源，伤害来源存活。
  can_trigger = function(self, event, target, player, data)
    local damage = data
    return target == player and player:hasSkill(self) 
    and damage.damage > 0 and damage.from and damage.from:isAlive()
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    --执行判定，判定如为锦囊牌，则触发效果。
    local room = player.room
    local damage = data
    local judge = {
      who = damage.from,
      reason = self.name,
      --TODO:把所有锦囊牌的名字写上去？
      pattern = ".|.|.|.|.|trick",
    }
    room:judge(judge)
    if judge.card.type == Card.TypeTrick then
      room:recover{
        who = damage.from,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
      room:changeMaxHp(player, -1)
    end
  end,
}

--------------------------------------------------
--萨比萌
--角色马克：可餐
--------------------------------------------------

local sabimeng_bimengjushou = General(extension,"sabimeng_bimengjushou", "individual", 6, 6, General.Female)
sabimeng_bimengjushou:addSkill(v_shihuan)
sabimeng_bimengjushou:addSkill(v_kecan)

--------------------------------------------------
--蟹袭
--技能马克：
--------------------------------------------------

local v_xiexi = fk.CreateTriggerSkill{
  name = "v_xiexi",
  --赋予特殊型技能定义
  anim_type = "special",
  --时机：手牌结算后
  events = {fk.CardUseFinished},
  --触发条件：结算的牌为红桃牌；遍历的角色存在此技能；当前回合角色及遍历的角色存活；遍历全场所有角色，存在角色持有该技能（据说这条不必要）。
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target:isAlive() and data.card.suit == Card.Heart
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if not target.chained then
      local prompt = "v_xiexi_chain:"..target.id
      --if VslUtil.yes_or_no(player, self.name, prompt) then
      if room:askForSkillInvoke(player, self.name, data, prompt) then
        return true
      end
    elseif target.chained then
      local prompt = "v_xiexi_damage:"..target.id
      --if VslUtil.yes_or_no(player, self.name, prompt) then
      if room:askForSkillInvoke(player, self.name, data, prompt) then
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    --遍历全场所有角色，对持有此技能的角色询问其是否发动技能。
    local room = player.room
    if target ~= player then
      --doindicate的两个参数一个为integer，一个为table
      room:doIndicate(player.id, { target.id })
    end
    if not target.chained then
      target:setChainState(true)
    elseif target.chained then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        damageType = fk.FireDamage,
        skillName = self.name,
      }
    end
  end,
}

--------------------------------------------------
--归影
--技能马克：
--------------------------------------------------

local v_guiying = fk.CreateTriggerSkill{
  name = "v_guiying",
  --赋予控场型技能定义
  anim_type = "control",
  --时机：角色离场时
  events = {fk.Death},
  --触发条件：触发时机的角色存在、触发时机的角色为遍历到的角色、触发时机的角色具有本技能。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self.name,false,true)
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  on_cost = function(self, event, target, player, data)
    --if self:isEffectable(player) then
    --制作一个囊括所有存活角色的table-targets，可以增加“技能发动者是否可以对对应角色使用技能”的判定，类似于caneffect函数。
    local room = player.room
    local alives = room:getAlivePlayers()
    local prompt = "#v_guiying_invoke"
    local targets = {}
    for _, p in ipairs(alives) do
      if VslUtil.SkillCanTarget(p, player, self.name) then
        table.insert(targets, p.id)
      end
    end
    --to：从targets中选择1个目标，是个值为number的table。
    local to = room:askForChoosePlayers(player, targets, 1, 1, prompt, self.name)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
    --end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    --通过ID找到对应的ServerPlayer
    local player_to = room:getPlayerById(self.cost_data)
    player_to:turnOver()
    local dummy = Fk:cloneCard("slash")
    dummy:addSubcards(player:getCardIds(Player.Hand))
    dummy:addSubcards(player:getCardIds(Player.Equip))
    dummy:addSubcards(player:getCardIds(Player.Judge))
    room:obtainCard(player_to.id, dummy, false,fk.ReasonPrey)
  end,
}

--------------------------------------------------
--阮卿言
--角色马克：
--------------------------------------------------

local ruanqingyan_hushanguiying = General(extension,"ruanqingyan_hushanguiying", "individual", 3, 3, General.Female)
ruanqingyan_hushanguiying:addSkill(v_xiexi)
ruanqingyan_hushanguiying:addSkill(v_guiying)

--------------------------------------------------
--奇虑
--------------------------------------------------

local v_qilvbuff = fk.CreateTargetModSkill{
  name = "#v_qilvbuff",
  residue_func = function(self, player, skill, scope)
    if player:hasSkill(self) and skill.trueName == "slash_skill" 
      and scope == Player.HistoryPhase then
      return -1
    end
  end,
}
local v_qilv = fk.CreateTriggerSkill{
  name = "v_qilv",
  --赋予输出型技能定义
  anim_type = "offensive",
  --时机：阶段变化时
  events = {fk.CardUseFinished},
  --触发条件：
  -- 触发时机的角色为遍历到的角色、遍历到的角色具有本技能，
  -- 使用的牌为锦囊牌，遍历到的角色可以使用杀。
  -- 注释：奇虑并非通常使用，所以不要带canuse，否则直接崩
  can_trigger = function(self, event, target, player, data)
    local slash = Fk:cloneCard("slash")
    return target == player and player:hasSkill(self) 
    -- and data.card.type == Card.TypeTrick and (not (not player:canUse(slash) or player:prohibitUse(slash)))
    and data.card.type == Card.TypeTrick and (not player:prohibitUse(slash))
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    -- local targets = table.filter(room:getOtherPlayers(player), function(p)
    --   return p
    -- end)
    local targets = {}
    local other = room:getOtherPlayers(player)
    local slash = Fk:cloneCard("slash")
    for _, p in ipairs(other) do
      if player:inMyAttackRange(p) and (not player:isProhibited(p, slash)) then
        table.insert(targets, p.id)
      end
    end
    local p = room:askForChoosePlayers(player, targets, 1, 1, "#v_qilv_askforslash", self.name)
    if #p > 0 then
      self.cost_data = p[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(self.cost_data)
    --阶段变化时，实现“是否跳出牌”的效果。
    local slash = Fk:cloneCard("slash")
    slash.skillName = self.name
    local new_use = {} ---@type CardUseStruct
    new_use.from = player.id
    --技能马克：可能会存在类似于知更酱多目标BUG的问题
    new_use.tos = { { tar.id } }
    new_use.card = slash
    -- new_use.skillName = self.name
    --测试skillName是否有效
    --print(new_use.skillName)
    room:useCard(new_use)
  end,
}
v_qilv:addRelatedSkill(v_qilvbuff)

--------------------------------------------------
--无前Namae
--------------------------------------------------

local wuqian_daweiba = General(extension,"wuqian_daweiba", "individual", 4, 4, General.Male)
wuqian_daweiba:addSkill(v_qilv)

--------------------------------------------------
--自愈
--------------------------------------------------

local v_ziyu = fk.CreateTriggerSkill{
  name = "v_ziyu",
  --赋予支援型技能定义
  anim_type = "support",
  --时机：阶段开始时，受到伤害后
  events = {fk.EventPhaseStart, fk.Damaged},
  --触发条件：
  --（阶段开始时）触发时机的角色为遍历到的角色、遍历到的角色具有本技能、本阶段为结束阶段、遍历角色体力值不为全场唯一最高。
  --（受到伤害后）触发时机的角色为遍历到的角色、遍历到的角色具有本技能、受到伤害的角色为遍历到的角色、遍历角色体力值不为全场唯一最高。
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    local damage = data
    --获取当前游戏除遍历到的角色外其他角色体力最大值。
    local other = room:getOtherPlayers(player)
    local other_max_hp = -999
    for _, p in ipairs(other) do
      if p.hp > other_max_hp then
        other_max_hp = p.hp
      end
    end
    if event == fk.EventPhaseStart then
      return target == player and player:hasSkill(self) 
      and player.phase == Player.Finish and player.hp <= other_max_hp
    elseif event == fk.Damaged then
      return target == player and player:hasSkill(self) and  damage.to == player and player.hp <= other_max_hp
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judge = {} ---@type JudgeStruct
    judge.who = player
    --这一条的意思是，出现黑桃花色条件后显示判定成功的特效
    judge.pattern = ".|.|spade"
    judge.reason = self.name
    room:judge(judge)
    if judge.card.suit == Card.Spade then
      --考虑到本作存在治疗过量概念，不需要角色受伤也可触发回复效果。
      --if player:isWounded() then 
      room:recover{
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
    end
  end,
}

--------------------------------------------------
--嗜血
--------------------------------------------------

local v_shixue = fk.CreateTriggerSkill{
  --（刚需）技能认证名
  name = "v_shixue",
  --(非必要）赋予支援型技能定义
  anim_type = "support",
  --时机：造成伤害后
  events = {fk.Damage},
  --触发条件：
  --存在触发时机的角色、触发时机的角色为遍历到的角色、遍历到的角色具有本技能、造成伤害的角色为遍历到的角色、造成伤害的卡牌颜色为黑色。
  can_trigger = function(self, event, target, player, data)
    local damage = data
    return target and target == player and player:hasSkill(self) and
        damage.from == player and damage.card.color == Card.Black
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  on_trigger = function(self, event, target, player, data)
    for i = 1, data.damage do
      if self.cost_data == "cancel" then
        self.cost_data = 0
        break
      end
      self:doCost(event, target, player, data)
    end
  end,
  on_cost = function(self, event, target, player, data)
    --if self:isEffectable(player) then
    local room = player.room
    -- for i = 1, data.damage do
    local choiceList = {}
    if player:isWounded() then 
      table.insert(choiceList, "recover_1")
    end
    table.insert(choiceList, "draw_1")
    table.insert(choiceList, "cancel")
    local choice = room:askForChoice(player, choiceList, self.name)
    if choice == "cancel" then
      self.cost_data = "cancel"
      return false
    elseif choice == "recover_1" then
      self.cost_data = 1
    elseif choice == "draw_1" then
      self.cost_data = 2
    end
    return true
    -- end
    --end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if self.cost_data == 1 then
      room:recover{
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name,
      }
    elseif self.cost_data == 2 then
      player:drawCards(1, self.name)
    end
  end,
}

--------------------------------------------------
--月下暗影
--------------------------------------------------

local yuexiaanying_juexingxuezu = General(extension,"yuexiaanying_juexingxuezu", "individual", 3, 5, General.Bigender)
yuexiaanying_juexingxuezu:addSkill(v_ziyu)
yuexiaanying_juexingxuezu:addSkill(v_shixue)

--------------------------------------------------
--忆狩
--技能马克：死了之后疑似还能发动忆狩。
--------------------------------------------------

local v_yishou_slash = fk.CreateTargetModSkill{
  name = "#v_yishou_slash",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill"
      and scope == Player.HistoryPhase and player:getMark("v_yishou_active-turn") > 0 then
      return player:getMark("v_yishou_active-turn")
    end
  end,
}
local v_yishou_mark = fk.CreateTriggerSkill{
  name = "#v_yishou_mark",
  --赋予卖血型技能定义
  anim_type = "masochism",
  --时机：阶段开始时，受到伤害后，摸牌时
  events = {fk.EventPhaseStart, fk.Damaged},
  --触发条件：
  --（阶段开始时）触发时机的角色为遍历到的角色、遍历到的角色具有本技能、本阶段为结束阶段、遍历到的角色存在且存活且体力>=1。
  --（受到伤害后）触发时机的角色为遍历到的角色、遍历到的角色具有本技能、受到伤害的角色为遍历到的角色、遍历到的角色存在且存活。
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    local damage = data
    if event == fk.EventPhaseStart then
      return target == player and player:hasSkill(self) 
      and player.phase == Player.Finish and player.hp >= 1
    elseif event == fk.Damaged then
      return target == player and player:hasSkill(self) and damage.to == player
      and damage.damage >= 1
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    --如果扳机为受到伤害后，根据体力值触发技能；否则正常触发。
    if event == fk.Damaged then
      for i = 1, data.damage do
        local prompt = "v_yishou_damage"
        local room = player.room
        if (not player:isNude()) then
          local ret = room:askForDiscard(player, 1, 1, true, self.name, true, ".", prompt)
          --需要的话在这里增加技能检测失效
          if #ret > 0 then
          --if room:askForDiscard(player, 1, 1, true, self.name, true) then
            return true
          end
        end
      end
    elseif event == fk.EventPhaseStart then
      --需要的话在这里增加技能检测失效;非锁定技想强制发动这里用个true就好啦
      local prompt = "v_yishou_end"
      --if VslUtil.yes_or_no(player, self.name, prompt) then
      if room:askForSkillInvoke(player, self.name, data, prompt) then
        --尝试了一下，这里不能跳阶段，失败的话只能耦合到on_use了。
        room:loseHp(player, 1, self.name)
        --大概要在这里做一个离场与否的判定，防止离场者技能继续发动。
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      room:addPlayerMark(player, "@v_yishou_count", 1)
    elseif event == fk.Damaged then
      room:addPlayerMark(player, "@v_yishou_count", 1)
    end
  end,
}
local v_yishou = fk.CreateTriggerSkill{
  name = "v_yishou",
  --赋予卖血型技能定义
  anim_type = "masochism",
  --时机：摸牌时
  events = {fk.DrawNCards},
  --触发条件：
  --（摸牌）触发时机的角色为遍历到的角色、遍历到的角色具有本技能、某个标记大于等于1、存在摸牌阶段。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMark("v_yishou_active-turn") > 0
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  on_use = function(self, event, target, player, data)
    local y = 2*player:getMark("v_yishou_active-turn")
    data.n = data.n + y
  end,
  refresh_events = {fk.EventPhaseChanging},
  can_refresh = function(self, event, target, player, data)
    return (data.from == Player.NotActive and data.to ~= Player.NotActive and target == player) 
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local x = player:getMark("@v_yishou_count")
    if x > 0 then
      room:sendLog{
        type = "#v_yishou_log",
        from = player.id,
        arg = 2*x,
        arg2 = x,
      }
      room:setPlayerMark(player, "v_yishou_active-turn", x)
      room:setPlayerMark(player, "@v_yishou_count", 0)
    end
  end,
}

v_yishou:addRelatedSkill(v_yishou_mark)
v_yishou:addRelatedSkill(v_yishou_slash)

--------------------------------------------------
--祭血
--技能马克：
--------------------------------------------------

local v_jixue = fk.CreateActiveSkill{
  name = "v_jixue",
  anim_type = "support",
  frequency = Skill.Limited,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  --target_num = 0,
  --card_num = 0,
  card_filter = function(self, to_select, selected, selected_targets)
    return false
  end,
  on_use = function(self, room, effect)
    --local players = room.players
    local from = room:getPlayerById(effect.from)
    --从两个区域换红色牌
    --local dummy = Fk:cloneCard("slash")
    local cards = {}
    table.insertTable(cards, from:getCardIds(Player.Hand))
    table.insertTable(cards, from:getCardIds(Player.Equip))
    local cards_throw = table.filter(cards, function(id)
      --这里后续可以追加玩家不可以弃置这张牌的判定，类似于鸡肋
      return Fk:getCardById(id).color == Card.Red and not from:prohibitDiscard(Fk:getCardById(id))
    end)
    --local x = #(dummy.subcards)
    local x = #(cards_throw)
    --print(x)
    if x > 0 then
      room:throwCard(cards_throw, self.name, from, from)
    end
    for i = 1, x do
      local choiceList = {}
      if from:isWounded() then 
        table.insert(choiceList, "recover_1")
      end
      table.insert(choiceList, "draw_1")
      local choice = room:askForChoice(from, choiceList, self.name)
      if choice == "recover_1" then
        room:recover{
          who = from,
          num = 1,
          recoverBy = from,
          skillName = self.name,
        }
      elseif choice == "draw_1" then
        from:drawCards(1, self.name)
      end
    end
  end,
}

--------------------------------------------------
--辻蓝佳音瑠
--角色马克：动画未实装
--------------------------------------------------

local laila_xuelie = General(extension,"laila_xuelie", "individual", 3, 3, General.Female)
laila_xuelie:addSkill(v_yishou)
laila_xuelie:addSkill(v_jixue)

--------------------------------------------------
--辨识
--技能马克：
--------------------------------------------------

local v_bianshi = fk.CreateActiveSkill{
  name = "v_bianshi",
  --赋予摸牌型技能定义
  anim_type = "drawcard",
  --可用条件：
  --出牌阶段限一次
  --角色手牌数<4+角色装备数
  can_use = function(self, player)
    local hands = {}
    local equips = {}
    table.insertTable(hands, player:getCardIds(Player.Hand))
    table.insertTable(equips, player:getCardIds(Player.Equip))
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
    and #(hands) < 4 + #(equips)
  end,
  card_filter = function(self, to_select, selected, selected_targets)
    return false
  end,
  on_use = function(self, room, effect)
    local players = room.players
    --记录手牌区及装备区的牌。
    local hands = {}
    local equips = {}
    local from = room:getPlayerById(effect.from)
    table.insertTable(hands, from:getCardIds(Player.Hand))
    table.insertTable(equips, from:getCardIds(Player.Equip))
    local x = 4 + #(equips)
    local draw_num = x - #(hands)
    if draw_num > 0 then
      room:sendLog{
        type = "#v_bianshi",
        from = from.id,
        arg = self.name,
        arg2 = x
      }
      room:drawCards(from, draw_num, self.name)
      room:askForDiscard(from, draw_num, draw_num, true, self.name, false)
    end
  end,
}

--------------------------------------------------
--成长
--------------------------------------------------

local v_chengzhang = fk.CreateTriggerSkill{
  name = "v_chengzhang",
  --赋予支援型技能定义
  anim_type = "support",
  --时机：体力回复后
  events = {fk.HpRecover},
  --触发条件：
  --（摸牌）造成回复的角色为遍历到的角色、遍历到的角色具有本技能、触发时机的角色体力==1。
  can_trigger = function(self, event, target, player, data)
    return data.recoverBy == player and player:hasSkill(self) 
    and target.hp == 1
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    --获取牌堆/弃牌堆中的装备牌。
    local allcards = {}
    table.insertTable(allcards, room.draw_pile)
    table.insertTable(allcards, room.discard_pile)
    local equips = table.filter(allcards, function(id)
      --（后续可以补充isavailable判定确保这个装备是可以被玩家装备的，如果出现玩家因为无法使用或装备区封印穿不上去的情况可以噶了。)
      local card = Fk:getCardById(id)
      return card.type == Card.TypeEquip
      and (not (not player:canUse(card) or player:prohibitUse(card)))
    end)
    if #equips > 0 then
      local x = #(equips)
      local c = math.random(1, x)
      local card = equips[c]
      --这种函数可以从表中随机选n个元素并返回一张表，如果n是nil，那么返回的就不是表而是单个元素
      --local card = table.random(equips, nil)
      local new_use = {} ---@type CardUseStruct
      new_use.from = player.id
      --技能马克：可能会存在类似于知更酱多目标BUG的问题
      new_use.tos = { { player.id } }
      new_use.card = Fk:getCardById(card)
      new_use.skillName = self.name
      room:useCard(new_use)
    end
  end,
}

--------------------------------------------------
--小毛
--角色马克：
--------------------------------------------------

local xiaomao_lairikeqi = General(extension,"xiaomao_lairikeqi", "individual", 4, 4, General.Female)
xiaomao_lairikeqi:addSkill(v_bianshi)
xiaomao_lairikeqi:addSkill(v_chengzhang)

--------------------------------------------------
--采集
--------------------------------------------------

local v_caiji = fk.CreateTriggerSkill{
  name = "v_caiji",
  --赋予控制型技能定义
  anim_type = "control",
  --时机：宣告手牌使用时
  events = {fk.AfterCardUseDeclared, fk.CardResponding},
  --触发条件：
  --触发时机的角色为遍历到的角色、遍历到的角色具有本技能
  --本回合此技能触发次数<1
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
      and player:usedSkillTimes(self.name, Player.HistoryTurn) < 1
      and player.hp > 0
  end,
  --使用条件：
  -- 卡牌使用宣告后：需要askforcard，存在且非虚拟牌则return true；
  -- 其他：return true
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local prompt = "#v_caiji_choice:::"..player.hp
    if room:askForSkillInvoke(player, self.name, data, prompt) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- local ids = {}
    local show_ids = {}
    --问题就出在这里，只要同时出现这个和可用的，直接爆炸。
    local cannot_choose_ids = {}
    local ids = room:getNCards(player.hp)
    -- for _,cd in ipairs(cards) do
    --   table.insert(ids, cd)
    -- end
    -- local foot_notes = {}
    for i = 1, #ids do
      local car = Fk:getCardById(ids[i])
      --print(car.suit)
      --print(data.card.suit)
      if car.suit ~= data.card.suit then
        table.insert(show_ids, ids[i])
      elseif car.suit == data.card.suit then
        table.insert(cannot_choose_ids, ids[i])
      end
    end
    --进入观看牌的环节
    if #show_ids > 0 then
      local to_return = table.random(show_ids, 1)
      local choice = "confirm"
      local result = room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseCardsAndChoiceBox.qml", {
        ids,
        {"confirm"},
        "#v_caiji_guankan_choice",
        {},
        1,
        1,
        cannot_choose_ids,
      })
      if result ~= "" then
        local reply = json.decode(result)
        to_return = reply.cards
        choice = reply.choice
      end
      if to_return[1] and to_return[1] ~= -1 then
        table.removeOne(ids, to_return[1])
        room:obtainCard(player, Fk:getCardById(to_return[1]), false, fk.ReasonPut)
      end
    end
    if #ids > 0 then
      room:askForGuanxing(player, ids, nil, {0, 0})
    end
  end,
}

--------------------------------------------------
--进化
--技能马克：
-- TODO：
-- 应援暂时不用管，等后续实装类似的通用技能再说。
--------------------------------------------------

local v_jinhua = fk.CreateTriggerSkill{
  name = "v_jinhua",
  --赋予特殊型技能定义
  anim_type = "special",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：目标确定后，卡牌移动后
  events = {fk.TargetSpecified, fk.AfterCardsMove},
  --触发条件：
  --（目标确定后）触发时机的角色为遍历到的角色；遍历到的角色具有本技能；
  --             使用的牌牌名为桃；
  --             被使用牌的目标体力<=0；
  --             被遍历到的角色不存在对应标记1。
  --（卡牌移动后）触发时机的角色为遍历到的角色；遍历到的角色具有本技能；条件1及条件2满足其中之一。
  --             （未完成）条件1：被遍历到的角色不存在对应标记2；被遍历到的角色处于回合外；
  --             遍历所有的牌牌移向被遍历到的角色；牌移向手牌区；牌移动的技能名不为“应援”（后补）。
  --             条件2：被遍历到的角色不存在对应标记2；被遍历到的角色装备区牌数量>=3。
  can_trigger = function(self, event, target, player, data)
    if event == fk.TargetSpecified then
      local room = player.room
      local targets = data
      local jinhua_tar = AimGroup:getAllTargets(targets.tos)
      return target == player and player:hasSkill(self)
      and data.card.name == "peach"
      and room:getPlayerById(jinhua_tar[1]).hp <= 0
      and player:getMark("v_jinhua_1") == 0
    elseif event == fk.AfterCardsMove then
      local room = player.room
      local equips = player:getCardIds(Player.Equip)
      local ret21 = false
      for _, d in ipairs(data) do
        if d.toArea == Player.Hand and d.to == player.id then
        --- and d.skillName ~= "LDyingyuan" 
          ret21 = true
        end
      end
      local ret2 = player:getMark("v_jinhua_2") == 0 and player.phase == Player.NotActive and ret21
      local ret3 = player:getMark("v_jinhua_3") == 0 and #equips >= 3
      return player:hasSkill(self) and not room:getTag("FirstRound") and ( ret2 or ret3 )
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    --增加对应的标记(暂时通过手牌进入的区域划分)。
    if event == fk.TargetSpecified then
      room:addPlayerMark(player, "v_jinhua_1", 1)
    elseif event == fk.AfterCardsMove then
      local ret22 = false
      for _, d in ipairs(data) do
        if d.toArea == Player.Hand then
          ret22 = true
        end
      end
      if ret22 == true then
        room:addPlayerMark(player, "v_jinhua_2", 1)
      elseif ret22 == false then
        room:addPlayerMark(player, "v_jinhua_3", 1)
      end
    end
    --增加一点体力上限，回复一点体力。
    room:changeMaxHp(player, 1)
    room:recover{
      who = player,
      num = 1,
      recoverBy = player,
      skillName = self.name,
    }
  end,
}

--------------------------------------------------
--奈伊
--------------------------------------------------

local naiyi_chongqunzhixin = General(extension, "naiyi_chongqunzhixin", "individual", 2, 2, General.Agender)
naiyi_chongqunzhixin:addSkill(v_caiji)
naiyi_chongqunzhixin:addSkill(v_jinhua)

--------------------------------------------------
--冰契
--技能马克：最佳时机为damageforseen，目前就用这俩时机；初步已写完，保险起见暂时隐藏本角色及本技能。
--技能描述：根据原Vup杀1.0.0.1版本，如果出现两个本技能持有者同场且全场（超过两人）均横置：
--①下家B攻击持有本技能的A，由A控制本次冰杀（其被视为伤害来源优先触发）
--②B攻击A以外任意角色，选择弃牌，铁索不解除，伤害不传导。
--②B攻击A以外任意角色，选择伤害，铁索解除，后续无论弃牌与否均传导。顺序为起始伤员-当前回合逆时针（从B开始算）
--------------------------------------------------

local v_bingqi = fk.CreateTriggerSkill{
  --（刚需）技能认证名
  name = "v_bingqi",
  --(非必要）赋予特殊型技能定义
  anim_type = "special",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：受到伤害时，造成伤害前
  -- events = {fk.DamageInflicted,fk.DamageCaused},
  -- events = {fk.PreDamage},
  events = {fk.DamageInflicted, fk.PreDamage},
  --触发条件：
  --（通用）触发时机的角色为遍历到的角色、遍历到的角色具有本技能、造成的伤害大于0，造成的伤害不为冰属性伤害。
  --（受到伤害时）牌为实体牌、牌的种类为锦囊牌、造成的伤害大于0。
  --（造成伤害时）造成伤害的来源为遍历到的角色、遍历到的角色具有本技能、牌为实体牌、牌的种类为锦囊牌、造成的伤害大于0。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) 
      and data.damage > 0 and data.damageType ~= fk.IceDamage
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.damageType = fk.IceDamage
    if data.to and data.to:hasSkill(self) then
      data.from = data.to
    end
    room:sendLog{
      type = "#v_bingqi_log",
      from = data.from.id,
      --log.to是数组
      to = {data.to.id},
      arg = self.name,
      arg2 = data.damage,
    }
  end,
}

--------------------------------------------------
--灵窟
--FIXME:逃课解决了非基本牌的问题，但存在无法取消的问题，请期待新月杀新版本。
--------------------------------------------------

local v_lingku = fk.CreateActiveSkill{
  name = "v_lingku",
  mute = true,
  anim_type = "special",
  --使用条件：
  -- 本回合只使用过一次技能；
  -- （待补充）对方可以被技能指定为目标，技能可以对对方生效。
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  target_num = 1,
  card_filter = function(self, to_select, selected, selected_targets)
    return false
  end,
  --目标选择：
  -- 选定角色数量为0，选定角色不为自己，选定角色的手牌数>=3；
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    local player = Fk:currentRoom().current
    return #selected == 0 and to_select ~= Self.id and target:getHandcardNum() >= 3
      and VslUtil.SkillCanTarget(target, player, self.name)
  end,
  --on_use内可以先加一个skillnullify的判定用来配合偷梁换柱和精算等技能无效化的东西
  -- （也希望这东西后续有更多优化吧）
  on_use = function(self, room, effect)
    --先随机选择对方三张手牌，根据是否为基本牌分门别类放好
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local ids = {}
    local show_ids = {}
    local cannot_choose_ids = {}
    local hand = target:getCardIds(Player.Hand)
    room:doAnimate("InvokeSkill", {
      name = self.name,
      player = player.id,
      skill_type = self.anim_type,
    })
    room:sendLog{
      type = "#v_skill_target",
      from = player.id,
      arg = self.name,
      to = { target.id }
    }
    player:broadcastSkillInvoke(self.name) --这个后续看效果 待定。
    for _,cd in ipairs(hand) do
      table.insert(ids, cd)
    end
    -- local foot_notes = {}
    while #show_ids < 3 do
      local random_one = table.random(ids)
      table.insert(show_ids, random_one)
      table.removeOne(ids, random_one)
      -- table.insert(foot_notes, target.general.."+hand_area")
      local ramcad = Fk:getCardById(random_one)
      if ramcad.type ~= Card.TypeBasic then
        table.insert(cannot_choose_ids, random_one)
      end
    end
    --进入观看牌的环节
    if #show_ids == 3 then
      -- room:fillAG(player, show_ids, cannot_choose_ids)
      --挣扎一下，但这玩意今天晚上玩下来感觉不太好。
      local to_return = table.random(show_ids, 1)
      local choice = "cancel"
      local result = room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseCardsAndChoiceBox.qml", {
        show_ids,
        {"confirm"},
        "#v_lingku_choice",
        {"cancel"},
        1,
        1,
        cannot_choose_ids,
      })
      if result ~= "" then
        local reply = json.decode(result)
        to_return = reply.cards
        choice = reply.choice
      end
      if to_return[1] and to_return[1] ~= -1 then
        --展示牌
        target:showCards(to_return[1])
        --摸牌
        --记录牌堆的同名牌。
        local can_get_ids = {}
        --这里没摸到牌堆/弃牌堆的牌
        local draw = room.draw_pile
        for _,p in ipairs(draw) do
          local card = Fk:getCardById(p)
          local idcard = Fk:getCardById(to_return[1])
          if card.name == idcard.name then
            table.insert(can_get_ids, p)
          end
        end
        if #can_get_ids > 0 then
          room:delay(500)
          local card_id = table.random(can_get_ids)
          room:obtainCard(target, Fk:getCardById(card_id), true, fk.ReasonPrey)
        else
          room:sendLog{
            type = "#v_player_find_fail",
            from = player.id,
            arg = self.name,
          }
        end
      end
    end
  end,
}

--------------------------------------------------
--牧野咲良
--角色马克：
-- 冰属性有待大量测试
--------------------------------------------------

local muyexiaoliang_dianyingdaiyuan = General(extension, "muyexiaoliang_dianyingdaiyuan", "individual", 3, 3, General.Female)
muyexiaoliang_dianyingdaiyuan:addSkill(v_bingqi)
muyexiaoliang_dianyingdaiyuan:addSkill(v_lingku)
-- muyexiaoliang_dianyingdaiyuan:addSkill(v_cheat)

--------------------------------------------------
--棋圣
--TODO:魔法剑
--------------------------------------------------

local v_qisheng = fk.CreateActiveSkill{
  name = "v_qisheng",
  anim_type = "drawcard",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name) == 0
  end,
  target_num = 0,
  min_card_num = 1,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:throwCard(effect.cards, self.name, player)
    if player:isAlive() then
      room:drawCards(player, #effect.cards, self.name)
      room:addPlayerMark(player, "@v_qisheng_card", #effect.cards)
      if player:getMark("@v_qisheng_card") >= 10 then
        room:notifySkillInvoked(player, self.name)
        player:broadcastSkillInvoke(self.name) --这个后续看效果 待定。
        --room:delay(2500)
        room:setPlayerMark(player, "@v_qisheng_card", 0)
        if not player:isKongcheng() then
          room:askForDiscard(player, 1, 1, false, self.name, false)
        end
        room:handleAddLoseSkills(player, "-v_qisheng|v_mogong_mfj|v_jiaojian_mfj", nil, true, false)
        --这里后续补获取魔法剑的方式
        for id = 0,500,1 do
          local card = Fk:getCardById(id)
          if card and card.name == "v_magicsword" then
            room:obtainCard(player, card, true)
          end
        end
      end
    end
  end
}

--------------------------------------------------
--魔法剑·魔攻
--------------------------------------------------

local v_mogong_mfj = fk.CreateTriggerSkill{
  name = "v_mogong_mfj",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      data.card.trueName == "slash"
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    --确认是否发动技能。
    local prompt = "v_mogong_mfj_choice"
    if room:askForSkillInvoke(player, self.name, data, prompt) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".|.|heart",
    }
    room:judge(judge)
    if judge.card.suit == Card.Heart then
      room:obtainCard(player, judge.card, true)
      data.disresponsive = true
    end
  end,
}

--------------------------------------------------
--魔法剑·交剑
--------------------------------------------------

local v_jiaojian_mfj = fk.CreateTriggerSkill{
  name = "v_jiaojian_mfj",
  events = {fk.AskForCardUse, fk.AskForCardResponse},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      (data.cardName == "jink" or (data.pattern and Exppattern:Parse(data.pattern):matchExp("jink|0|nosuit|none")))
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    --确认是否发动技能。
    local prompt = "v_jiaojian_mfj_choice"
    if room:askForSkillInvoke(player, self.name, data, prompt) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judgeData = {
      who = player,
      reason = self.name,
      pattern = ".|.|spade",
    }
    room:judge(judgeData)

    if judgeData.card.suit == Card.Spade then
      room:obtainCard(player, judgeData.card, true)
      if event == fk.AskForCardUse then
        data.result = {
          from = player.id,
          card = Fk:cloneCard('jink'),
        }
        data.result.card.skillName = self.name

        if data.eventData then
          data.result.toCard = data.eventData.toCard
          data.result.responseToEvent = data.eventData.responseToEvent
        end
      else
        data.result = Fk:cloneCard('jink')
        data.result.skillName = self.name
      end

      return true
    end
  end
}

--------------------------------------------------
--水柳暮玥
--------------------------------------------------

local shuiliumuyue_benzhaimonv = General(extension, "shuiliumuyue_benzhaimonv", "individual", 4, 4, General.Agender)
shuiliumuyue_benzhaimonv:addSkill(v_qisheng)
shuiliumuyue_benzhaimonv:addRelatedSkill(v_mogong_mfj)
shuiliumuyue_benzhaimonv:addRelatedSkill(v_jiaojian_mfj)

--------------------------------------------------
--娴静
--------------------------------------------------

local v_xianjing = fk.CreateTriggerSkill{
  name = "v_xianjing",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  --触发条件：
  -- 遍历到的角色持有该技能；
  -- 触发时机的角色处于准备阶段;
  -- 触发时机的角色判定区中存在牌。
  -- （待补充）技能没有被无效；遍历到的角色的技能可以对触发时机的角色产生影响。
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and
      target.phase == Player.Start and
      #target:getCardIds(Player.Judge) > 0
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    --确认是否发动技能。
    local prompt = "v_xianjing_choice:"..target.id
    if room:askForSkillInvoke(player, self.name, data, prompt) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = {}
    if player.id ~= target.id then
      room:doIndicate( player.id, {target.id} )
    end
    target:turnOver()
    --测试用，放到牌堆顶
    -- room:moveCardTo(target:getCardIds(Player.Judge), Card.DrawPile, nil, fk.ReasonJustMove, self.name, nil, true)
    -- local ram = math.random(1, #room.draw_pile + 1)
    -- room:moveCards({
    --   ids = target:getCardIds(Player.Judge),
    --   from = target.id,
    --   toArea = Card.DrawPile,
    --   moveReason = fk.ReasonJustMove,
    --   skillName = self.name,
    --   drawPilePosition = ram,
    -- })
    VslUtil.return_draw_pile(target, target:getCardIds(Player.Judge), self.name)
    room:delay(250)
  -- end
  end
}

--------------------------------------------------
--儒琴
--TODO：后续可以关注一下儒琴和奇遇的配合方式，后续处理；可能需要涉及所有伤害计算方式的修改。
-- 目前倾向于最多额外出牌阶段相比于原版可以多开一次儒琴
-- 但额外回合使用的儒琴应该不会影响到自己的正常回合。
--------------------------------------------------

local v_ruqin = fk.CreateTriggerSkill{
  name = "v_ruqin",
  --赋予进攻型技能定义
  anim_type = "offensive",
  --时机：阶段结束时
  events = {fk.EventPhaseEnd},
  --触发条件：
  --（阶段结束时）触发时机的角色为遍历到的角色；遍历到的角色具有本技能；
  --              被遍历到的角色处于出牌阶段。
  --              被遍历到的角色本回合未造成伤害，被遍历到的角色存在出牌阶段
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
    and player.phase == Player.Play
    and player:getMark("#turn_damage-turn") == 0 and VslUtil.exist_or_not(player, Player.Play) 
  end,
  on_cost = function(self, event, target, player, data)
    --确认是否发动技能。
    local room = player.room
    local targets = {}
    local others = room:getOtherPlayers(player, true, false)
    local prompt = "v_ruqin_ask"
    for _,p in ipairs(others) do
      local pm = p:getMark("#target_specified-turn")
      local mycr = false
      if pm ~= 0 then
        for _,t in ipairs(pm) do
          if t == player.id then
            mycr = true
            break
          end
        end
      end
      if mycr then
        --后续可以在这里补充以下判定：
        -- caneffect。
        if VslUtil.SkillCanTarget(p, player, self.name) then
          table.insert(targets, p.id)
        end
      end
    end
    local ret = room:askForChoosePlayers(player, targets, 1, 1, prompt, self.name, true)
    --确认是否发动技能。
    if #ret > 0 then
      --后续可以在这里补充以下判定：
      -- 遍历到的角色本技能未被元初之类的。
      self.cost_data = ret[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(self.cost_data)
    tar:drawCards(1, self.name)
    room:damage{
      from = player,
      to = tar,
      damage = 1,
      skillName = self.name,
    }
  end,
}

--------------------------------------------------
--梦音茶糯
--------------------------------------------------

local mengyinchanuo_xiuwaihuizhong = General(extension, "mengyinchanuo_xiuwaihuizhong", "individual", 3, 3, General.Female)
mengyinchanuo_xiuwaihuizhong:addSkill(v_xianjing)
mengyinchanuo_xiuwaihuizhong:addSkill(v_ruqin)

--------------------------------------------------
--止鸽
--------------------------------------------------

local v_zhige_gugu = fk.CreateActiveSkill{
  name = "v_zhige_gugu",
  anim_type = "support",
  card_num = 1,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) < 1
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "slash"
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    -- room:addPlayerMark(player, "v_Not_clear_card_flag", 1)
    room:obtainCard(target, effect.cards[1], false, fk.ReasonGive)
    -- room:addPlayerMark(player, "v_Not_clear_card_flag", 0)
    room:addCardMark(Fk:getCardById(effect.cards[1]), "@@v_zhige_gugu-cm!l*", 1)
    room:drawCards(player, 1, self.name)
  end,
}
local v_zhige_gugu_recover = fk.CreateTriggerSkill{
  name = "#v_zhige_gugu_recover",
  mute = true,
  anim_type = "recover",
  --时机：卡牌移动前，卡牌移动后
  events = {fk.BeforeCardsMove, fk.AfterCardsMove},
  --触发条件：
  -- 卡牌移动前：
  --  牌移动原因为弃置
  --  牌移动的目标为弃牌堆/处理区
  --  牌数大于0
  --  存在卡牌存在对应标记
  -- 卡牌移动后：
  --  牌移动原因为弃置
  --  牌移动的目标为弃牌堆/处理区
  --  牌数大于0
  --  存在卡牌存在对应标记
  can_trigger = function(self, event, target, player, data)
    if event == fk.BeforeCardsMove then
      for _, move in ipairs(data) do
        if move.moveReason == fk.ReasonDiscard 
          and (move.toArea == Card.DiscardPile or move.toArea == Card.Processing)
          -- and #move.ids > 0 
        then
          for _, info in ipairs(move.moveInfo) do
            local dis_card = Fk:getCardById(info.cardId)
            if dis_card and dis_card:getMark("@@v_zhige_gugu-cm!l*") > 0 then
              return true
            end
          end
        end
      end
    elseif event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.moveReason == fk.ReasonDiscard 
          and (move.toArea == Card.DiscardPile or move.toArea == Card.Processing)
          -- and #move.ids > 0 
        then
          for _, info in ipairs(move.moveInfo) do
            local dis_card = Fk:getCardById(info.cardId)
            if dis_card and dis_card:getMark("v_zhige_gugu_trigger") > 0 then
              return true
            end
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    return true
  end,
  --使用流程：
  -- 卡牌移动后：
  --   为遍历到的角色提供特定标记
  on_use = function(self, event, target, player, data)
    --遍历全场所有存活角色，挑出其中未被横置的角色。
    local room = player.room
    if event == fk.BeforeCardsMove then
      for _, move in ipairs(data) do
        for _, info in ipairs(move.moveInfo) do
          local dis_card = Fk:getCardById(info.cardId)
          if dis_card and dis_card:getMark("@@v_zhige_gugu-cm!l*") > 0 then
            room:setCardMark(dis_card, "v_zhige_gugu_trigger", 1)
          end
        end
      end
    elseif event == fk.AfterCardsMove then
      local pla
      local dis_card
      for _, move in ipairs(data) do
        for _, info in ipairs(move.moveInfo) do
          dis_card = Fk:getCardById(info.cardId)
          if dis_card and dis_card:getMark("v_zhige_gugu_trigger") > 0 then
            room:setCardMark(dis_card, "v_zhige_gugu_trigger", 0)
            pla = room:getPlayerById(move.from)
            if pla and pla:isAlive() then
              room:sendLog{
                type = "#v_zhige_gugu_recover_log",
                from = pla.id,
                card = { dis_card.id },
                arg = "@@v_zhige_gugu-cm!l*",
              }
              room:recover({
                who = pla,
                num = 1,
                skillName = "v_zhige_gugu"
              })
            end
          end
        end
      end
    end
  end,
}

v_zhige_gugu:addRelatedSkill(v_zhige_gugu_recover)

--------------------------------------------------
--医怀
--这玩意还在报错，原因暂时不明
--------------------------------------------------

local v_yihuai = fk.CreateTriggerSkill{
  name = "v_yihuai",
  mute = true,
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.CardEffectCancelledOut},
  --使用条件：
  --...
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    return player:hasSkill(self)
      and data.card and data.card.trueName == "slash" and data.card.id > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if room:getCardArea(data.card) == Card.Processing then
      room:notifySkillInvoked(player, self.name)
      player:broadcastSkillInvoke(self.name)
      room:obtainCard(player.id, data.card, true, fk.ReasonJustMove)
    end
  end,
}

--------------------------------------------------
--露蒂丝
--------------------------------------------------

local ludisi_guguyisheng = General(extension, "ludisi_guguyisheng", "individual", 3, 3, General.Female)
ludisi_guguyisheng:addSkill(v_zhige_gugu)
ludisi_guguyisheng:addSkill(v_yihuai)

--------------------------------------------------
--紫禁
--------------------------------------------------

local v_zijin = fk.CreateTriggerSkill{
  name = "v_zijin",
  mute = true,
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  --触发条件：
  -- 触发时机的角色为遍历到的角色，遍历到的角色持有该技能；
  -- 触发时机的角色处于结束阶段;
  -- 触发时机的角色本回合未造成伤害；
  -- 触发时机的角色有牌。
  -- （待补充）技能没有被无效；遍历到的角色的技能可以对触发时机的角色产生影响。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
      and player.phase == Player.Finish
      and player:getMark("#turn_damage-turn") == 0
      and (not player:isNude())
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = {}
    local others = room:getOtherPlayers(player, true, false)
    local prompt = "v_zijin_ask"
    for _,p in ipairs(others) do
      --后续可以在这里补充以下判定：
      -- caneffect，目标可以弃置遍历到的角色的牌(candiscard)。
      if VslUtil.SkillCanTarget(p, player, self.name) then
        table.insert(targets, p.id)
      end
    end
    local ret = room:askForChoosePlayers(player, targets, 1, 1, prompt, self.name, true)
    --确认是否发动技能。
    if #ret > 0 then
      --后续可以在这里补充以下判定：
      -- 遍历到的角色本技能未被元初之类的无效，目标可以弃置遍历到的角色的牌。
      self.cost_data = ret[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = room:getPlayerById(self.cost_data)
    room:doAnimate("InvokeSkill", {
      name = self.name,
      player = player.id,
      skill_type = self.anim_type,
    })
    room:sendLog{
      type = "#v_skill_target",
      from = player.id,
      arg = self.name,
      to = { targets.id }
    }
    player:broadcastSkillInvoke(self.name)
    local throw_id = room:askForCardChosen(targets, player, "he", self.name)
    room:throwCard(throw_id, self.name, player, targets)
    local car = Fk:getCardById(throw_id)
    if car.type == Card.TypeBasic then
      room:setTag("RoundCount", room:getTag("RoundCount") + 2)
      local pls = room.players
      --为全体玩家更新轮数
      for _,p in ipairs(pls) do
        p:doNotify("UpdateRoundNum", room:getTag("RoundCount") or 0)
      end
      room:sendLog{
        type = "#v_addround",
        arg = self.name,
        arg2 = room:getTag("RoundCount"),
      }
    else
      room:damage{
        from = player,
        to = targets,
        damage = 1,
        skillName = self.name,
      }
    end
  -- end
  end
}

--------------------------------------------------
--本怖
--------------------------------------------------

local v_benbu = fk.CreateTriggerSkill{
  name = "v_benbu",
  frequency = Skill.Wake,
  anim_type = "support",
  events = {fk.RoundStart},
  --触发条件：
  -- 遍历到的角色持有该技能；
  -- 遍历到的角色未使用过该技能
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  --觉醒条件：进行一次判定，结果点数<=游戏轮数则觉醒
  can_wake = function(self, event, target, player, data)
    local room = player.room
    local pattern = ".|1~" .. room:getTag("RoundCount")
    local judge = {
      who = player,
      reason = self.name,
      pattern = pattern,
    }
    room:judge(judge)
    local num = judge.card.number
    return num <= room:getTag("RoundCount")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    --后续这里可以补充动画和配音，以及角色图片&称号的变化。
    --回复一点体力并获得技能。
    room:recover({
      who = player,
      num = 1,
      recoverBy = player,
      skillName = self.name
    })
    room:handleAddLoseSkills(player, "v_chushou", nil)
  end,
}

--------------------------------------------------
--触手
--------------------------------------------------

local v_chushou_buff = fk.CreateMaxCardsSkill{
  name = "#v_chushou_buff",
  correct_func = function(self, player)
    if player:getMark("@v_chushou") > 0 then
      return -player:getMark("@v_chushou")
    end
  end,
}
local v_chushou = fk.CreateTriggerSkill{
  name = "v_chushou",
  --赋予控场型技能定义
  anim_type = "control",
  frequency = Skill.Compulsory,
  --时机：受到伤害后
  events = {fk.Damaged},
  --触发条件：（这部分没写完）
  -- 触发时机的角色为遍历到的角色；遍历到的角色具有本技能；
  -- 伤害大于0，存在伤害源
  -- 伤害源不为遍历到的角色
  -- （待补充）技能可以对对方生效。
  can_trigger = function(self, event, target, player, data)
    local damage = data
    return target == player and player:hasSkill(self) 
    and damage.damage > 0 
    and damage.from and damage.from:isAlive()
    and damage.from ~= player
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- if player.id ~= data.from.id then
    room:doIndicate( player.id, {data.from.id} )
    -- end
    room:delay(250)
    room:addPlayerMark(data.from, "@v_chushou", 1)
    room:addPlayerMark(player, "@v_chushou", 1)
    room:damage{
      from = player,
      to = data.from,
      damage = 1,
      skillName = self.name,
    }
  end,
}

v_chushou:addRelatedSkill(v_chushou_buff)

--------------------------------------------------
--夏卜卜
--------------------------------------------------

local xiabubu_zhixingjiejie = General(extension, "xiabubu_zhixingjiejie", "individual", 4, 4, General.Agender)
xiabubu_zhixingjiejie:addSkill(v_zijin)
xiabubu_zhixingjiejie:addSkill(v_benbu)
xiabubu_zhixingjiejie:addRelatedSkill(v_chushou)

--------------------------------------------------
--神伴
--技能马克:后续可以补充光神的图片
--技能马克2：原Vup V1.0.1版本中技能指定顺序为ABCABC
--      但根据FK主创团队的说法，这里排序规则应该是AABBCC
--      如需维持原有规律，请参考“丰姿”
--------------------------------------------------

local v_shenban = fk.CreateActiveSkill{
  name = "v_shenban",
  anim_type = "support",
  can_use = function(self, player)
    return (not player:isNude())
  end,
  target_num = 1,
  card_num = 1,
  --可以弃置此牌，此牌颜色为红色。
  card_filter = function(self, to_select, selected, selected_targets)
    if #selected == 1 then return false end
    local card = Fk:getCardById(to_select)
    return card.color == Card.Red and (not Self:prohibitDiscard(card))
  end,
  --（待补充）canuse
  target_filter = function(self, to_select, selected)
    -- local target = Fk:currentRoom():getPlayerById(to_select)
    local target = Fk:currentRoom():getPlayerById(to_select)
    local player = Fk:currentRoom().current
    --可以在这里后续加caneffect
    return #selected == 0
      and VslUtil.SkillCanTarget(target, player, self.name)
    -- return #selected == 0
  end,
  --后续可以在这里补充元初类判定
  on_use = function(self, room, effect)
    --先拼点
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player)
    room:addPlayerMark(target, "@v_shenban", 1)
    if player.phase == Player.Play then
      player.room.logic:getCurrentEvent():findParent(GameEvent.Phase):shutdown()
    end
  end,
}
local v_shenban_tar = fk.CreateTriggerSkill{
  name = "#v_shenban_tar",
  --赋予输出型技能定义,
  anim_type = "offensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  mute = true,
  events = {fk.TargetSpecified},
  --触发条件：
  --             触发时机的角色为遍历到的角色，遍历到的角色存在神伴标记
  --             触发的牌真名为杀或为普通锦囊牌，触发的牌为实体牌
  --             本次流程中第一次触发这个时机（待定）
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("@v_shenban") > 0
    and (data.card.trueName == "slash" or (data.card.type == Card.TypeTrick and
    data.card.sub_type ~= Card.SubtypeDelayedTrick)) and data.card.id > 0
    and data.firstTarget
  end,
  --关于data.targetGroup和data.tos的区别后续可以用dbg处理
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:removePlayerMark(player, "@v_shenban", 1)
    local address = "./packages/"..VslUtil.extensionName.."/image/anim/v_shenban"
    room:setEmotion(player, address)
    local tarold = AimGroup:getAllTargets(data.tos)
    local tarnew = {}
    for _, p in ipairs(tarold) do
      TargetGroup:pushTargets(data.targetGroup, p)
      table.insert(tarnew, p)
      table.insert(tarnew, p)
    end
    --注释：发log用的to是一维数组，而tos是二维数组
    if not data.card:isVirtual() then
      room:sendLog{
        type = "#v_changetarget_log",
        from = player.id,
        to = tarnew,
        arg = self.name,
        card = { data.card.id },
      }
    elseif data.card:isVirtual() then
      room:sendLog{
        type = "#v_changetarget_virtual_log",
        from = player.id,
        to = tarnew,
        arg = self.name,
        arg2 = data.card:toLogString(),
      }
    end

  end,
}

--由于世界名画“五谷丰登和无懈可击”，这玩意还需要完善下再拿出去···
-- local v_shenban_tar = fk.CreateTriggerSkill{
--   name = "#v_shenban_tar",
--   --赋予输出型技能定义,
--   anim_type = "offensive",
--   --技能为锁定技，满足条件后强制发动
--   frequency = Skill.Compulsory,
--   events = {fk.AfterCardTargetDeclared},
--   --使用条件：
--   --             触发时机的角色为遍历到的角色，遍历到的角色存在神伴标记
--   --             触发的牌真名为杀或为普通锦囊牌，触发的牌为实体牌
--   can_trigger = function(self, event, target, player, data)
--     return target == player and player:getMark("@v_shenban") > 0
--     and (data.card.trueName == "slash" or (data.card.type == Card.TypeTrick and
--     data.card.sub_type ~= Card.SubtypeDelayedTrick)) and data.card.id > 0
--   end,
--   -- on_cost = function(self, event, target, player, data)
--   --   local type = data.card:getTypeString()
--   --   return #player.room:askForDiscard(player, 1, 1, false, self.name, true, ".|.|.|.|.|"..type,
--   --     "#fengzi-invoke:::"..type..":"..data.card:toLogString()) > 0
--   -- end,
--   on_use = function(self, event, target, player, data)
--     local room = player.room
--     room:removePlayerMark(player, "@v_shenban", 1)
--     room:setPlayerMark(player, self.name, TargetGroup:getRealTargets(data.tos))
--   end,

--   refresh_events = {fk.CardUseFinished},
--   can_refresh = function(self, event, target, player, data)
--     return target == player and player:hasSkill(self.name, true) and player:getMark(self.name) ~= 0
--   end,
--   on_refresh = function(self, event, target, player, data)
--     local room = player.room
--     room:setEmotion(player, "./packages/vupslash/image/anim/v_shenban")
--     local targets = player:getMark(self.name)
--     room:setPlayerMark(player, self.name, 0)
--     for _, id in ipairs(targets) do
--       if room:getPlayerById(id).dead then
--         table.removeOne(targets, id)
--       end
--     end
--     if #targets > 0 then
--       --注释：发log用的to是一维数组，而tos是二维数组
--       room:sendLog{
--         type = "#v_shenban_log",
--         from = player.id,
--         -- to = targets,
--         arg = self.name,
--         card = { data.card.id },
--       }
--       --这牌要不要把原牌带的技能带上后续再说。
--       room:useVirtualCard(data.card.name, nil, player, table.map(targets, function(id) return room:getPlayerById(id) end), self.name, true)
--     end
--   end,
-- }

v_shenban:addRelatedSkill(v_shenban_tar)

--------------------------------------------------
--逝随
--------------------------------------------------

local v_shisui = fk.CreateTriggerSkill{
  name = "v_shisui",
  anim_type = "support",
  events = {fk.EnterDying},
  --使用条件：
  --  遍历到的角色具有本技能
  --  触发时机的角色存在且不为遍历到的角色，触发时机的角色体力小于1
  --  （待补充）not skillnullify，player:caneffect
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) 
    and target and target ~= player and target.hp <1 
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForSkillInvoke(player, self.name, data)
    return choice
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if target ~= player then
      --doindicate的两个参数一个为integer，一个为table
      room:doIndicate(player.id, { target.id })
    end
    --降低一点体力上限，回复对方一点体力。
    room:changeMaxHp(player, -1)
    room:recover{
      who = target,
      num = 1,
      recoverBy = player,
      skillName = self.name,
    }
    -- room:setPlayerMark(target, "v_shisui_alive", 1)
    -- data.extra_data.shisui = target.id
    -- 如果以下条件存在，触发后续机制：
    --  触发时机的角色存在且存活，触发时机的角色存在牌
    if target and target:isAlive() and not target:isAllNude() then
      local ids = {}
      local ids_loc = {}
      local take_ids = {}
      -- local show_ids = {}
      -- local can_choose_ids = {}
      local cannot_choose_ids = {}
      local hand = target:getCardIds(Player.Hand)
      local equip = target:getCardIds(Player.Equip)
      local judge = target:getCardIds(Player.Judge)
      for _,cd in ipairs(hand) do
        table.insert(ids, cd)
        table.insert(ids_loc, {cd, hand})
      end
      for _,cd in ipairs(equip) do
        table.insert(ids, cd)
        table.insert(ids_loc, {cd, equip})
      end
      for _,cd in ipairs(judge) do
        table.insert(ids, cd)
        table.insert(ids_loc, {cd, judge})
      end
      --进入拿牌环节
      while #ids ~= #cannot_choose_ids do
        -- room:fillAG(player, show_ids, cannot_choose_ids)
        room:fillAG(player, ids)
        for _,p in ipairs(cannot_choose_ids) do
          room:takeAG(target, p, room.players)
          -- table.removeOne(ids, p)
        end
        local id1 = room:askForAG(player, ids, false, self.name)
        -- local id1 = room:askForAG(player, can_choose_ids, true, self.name)
        if id1 and id1 ~= -1 then
          room:closeAG(player)
          -- dummy:addSubcard(id1)
          local card1 = Fk:getCardById(id1)
          table.insert(take_ids, id1)
          for _,cd in ipairs(ids_loc) do
            local car = Fk:getCardById(cd[1])
            if car == card1 then
              for _,cd in ipairs(cd[2]) do
                table.insert(cannot_choose_ids, cd)
              end
            end
          end
        end
      end
      if #take_ids > 0 then
        room:moveCards({
          ids = take_ids,
          from = target.id,
          to = player.id,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonPrey,
        })
        -- room.obtainCard(player, dummy, false, fk.ReasonPrey)  --等会用movecard试试
      end
    end
    -- elseif event == fk.AfterDying then
    --   return true
    -- end
  end,
}

-- 本版本暂时废弃
-- local v_shisui = fk.CreateTriggerSkill{
--   name = "v_shisui",
--   anim_type = "support",
--   events = {fk.EnterDying, fk.AfterDying},
--   --使用条件：
--   -- 进入濒危状态:
--   --  遍历到的角色具有本技能
--   --  触发时机的角色存在且不为遍历到的角色，触发时机的角色体力小于1
--   --  （待补充）not skillnullify，player:caneffect
--   -- 脱离濒危状态:
--   --  遍历到的角色具有本技能（为了防止插结失去技能，可以删掉）
--   -- 触发时机的角色存在且存活，触发时机的角色存在牌，触发时机的角色存在标记（待定）
--   -- 注释：这个标记需要在玩家死亡后可以自动被清理掉的能力，先按照会被清洗掉交给触发时机的角色。
--   can_trigger = function(self, event, target, player, data)
--     if event == fk.EnterDying then
--       return player:hasSkill(self) 
--       and target and target ~= player and target.hp <1 
--     elseif event == fk.AfterDying then
--       return player:hasSkill(self) 
--         and target and target:isAlive() and not target:isAllNude() 
--         and data.extra_data.shisui == target.id
--     end
--   end,
--   on_cost = function(self, event, target, player, data)
--     if event == fk.EnterDying then
--       local room = player.room
--       local choice = room:askForSkillInvoke(player, self.name, data)
--       return choice
--     elseif event == fk.AfterDying then
--       return true
--     end
--   end,
--   on_use = function(self, event, target, player, data)
--     local room = player.room
--     if event == fk.EnterDying then
--       if target ~= player then
--         --doindicate的两个参数一个为integer，一个为table
--         room:doIndicate(player.id, { target.id })
--       end
--       --降低一点体力上限，回复对方一点体力。
--       room:changeMaxHp(player, -1)
--       room:recover{
--         who = target,
--         num = 1,
--         recoverBy = player,
--         skillName = self.name,
--       }
--       -- room:setPlayerMark(target, "v_shisui_alive", 1)
--       data.extra_data.shisui = target.id
--     elseif event == fk.AfterDying then
--       return true
--     end
--   end,
-- }

--------------------------------------------------
--绫濑光
--------------------------------------------------

local linglaiguang_shengsixiangyi = General(extension, "linglaiguang_shengsixiangyi", "individual", 4, 4, General.Agender)
linglaiguang_shengsixiangyi:addSkill(v_shenban)
linglaiguang_shengsixiangyi:addSkill(v_shisui)
-- linglaiguang_shengsixiangyi:addSkill(v_lose)
-- linglaiguang_shengsixiangyi:addSkill(v_cheat)

--------------------------------------------------
--血林
--------------------------------------------------

local v_xuelin = fk.CreateTriggerSkill{
  name = "v_xuelin",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) 
    and data.from and not data.from.dead
      and data.damage > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local from = data.from
    if from and player ~= from then room:doIndicate(player.id, {from.id}) end
    local judge = {
      who = from,
      reason = self.name,
      pattern = ".",
    }
    room:judge(judge)
    if judge.card.color == Card.Red then
      room:damage{
        from = player,
        to = from,
        damage = 1,
        skillName = self.name,
      }
    elseif judge.card.color == Card.Black then
      room:askForDiscard(from, 2, 2, true, self.name, false)
    end
  end,
}

--------------------------------------------------
--寻腥
--------------------------------------------------

local v_xunxing = fk.CreateTriggerSkill{
  name = "v_xunxing",
  anim_type = "defensive",
  events = {fk.DamageInflicted},
  --使用条件：（已完成）
  -- 伤害>0，存在源与目标；
  -- 遍历到的角色在源的攻击范围内，目标为触发时机的角色，触发时机的角色不为遍历到的角色；
  -- 遍历到的角色区域内有牌，遍历到的角色具有本技能。
  can_trigger = function(self, event, target, player, data)
    return data.damage > 0 
    --  and data.from and data.to
     and data.from and data.from:inMyAttackRange(player) and (data.to or {}) == target and target ~= player
     and not player:isNude() and player:hasSkill(self)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local prompt = "v_xunxing_ask:"..target.id
    local card = room:askForCard(player, 1, 1, true, self.name, true, ".", prompt)[1]
    if card then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card = Fk:getCardById(self.cost_data)
    room:moveCardTo(card, Card.DrawPile, nil, fk.ReasonPut, self.name, nil, false)
    room:damage{
      from = data.from,
      to = player,
      damage = data.damage,
      damageType = data.damageType,
      skillName = self.name,
      card = data.card,
    }
    return true
  end,
}

--------------------------------------------------
--奈奈莉娅
--------------------------------------------------

local nainailiya_yuanbenlinyuan = General(extension, "nainailiya_yuanbenlinyuan", "individual", 4, 4, General.Female)
nainailiya_yuanbenlinyuan:addSkill(v_xuelin)
nainailiya_yuanbenlinyuan:addSkill(v_xunxing)

--------------------------------------------------
--炽翎
--TODO:如果在展示牌之后出现因为其他技能导致的弃置需要思考方案
--------------------------------------------------

local v_chiling = fk.CreateViewAsSkill{
  name = "v_chiling",
  anim_type = "offensive",
  pattern = "fire_attack",
  card_filter = function(self, to_select, selected)
    local card = Fk:getCardById(to_select)
    return #selected == 0 and card.color == Card.Red
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local c = Fk:cloneCard("fire_attack")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
}
local v_chiling_next = fk.CreateTriggerSkill{
  name = "#v_chiling_next",
  anim_type = "offensive",
  mute = true,
  --时机：卡牌使用宣告后，卡牌移动后，伤害造成时
  events = {fk.AfterCardUseDeclared, fk.AfterCardsMove, fk.DamageCaused},
  --使用条件：
  -- 卡牌使用宣告后：触发时机的角色为遍历到的角色，遍历到的角色存在此技能
  --                遍历到的角色存在手牌，牌名为火攻，
  --                牌的技能名为v_chiling；
  -- 卡牌移动后：遍历到的角色存在此技能
  --            存在特定mark，弃牌skillname为火攻，弃牌原因为弃置【如果不对，后续用dbg查】；
  -- 伤害造成时：触发时机的角色为遍历到的角色，遍历到的角色存在此技能
  --             伤害>0，造成伤害的牌为火攻，
  --             造成伤害的牌的技能名为v_chiling，存在特定mark。
  can_trigger = function(self, event, target, player, data)
    if event == fk.AfterCardUseDeclared then
      return target == player and player:hasSkill(self) 
        and (not player:isKongcheng()) and data.card and data.card.name == "fire_attack"
        and data.card.skillName == "v_chiling"
        -- and table.contains(data.card.skillNames, "v_chiling")
    elseif event == fk.AfterCardsMove then
      local room = player.room
      local move = data
      --后续discardpile可能删掉
      if player:hasSkill(self) and (not (player:getMark("v_chiling_id") > 0) and move.skillName == "fire_attack"
      and move.from == player.id 
      and move.toArea == Card.DiscardPile
      ) then
        return false
      end
      for _, move in ipairs(data) do
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand 
            and (room:getCardArea(info.cardId) == Card.DiscardPile or room:getCardArea(info.cardId) == Card.Processing)
            and info.cardId == player:getMark("v_chiling_id") then
            return true
          end
        end
      end
    elseif event == fk.DamageCaused then
      return target == player and player:hasSkill(self) 
        and data.damage > 0 and data.card and data.card.name == "fire_attack" 
        and data.card and data.card.skillName == "v_chiling" and player:getMark("v_chiling_damage") > 0
        -- and data.card and table.contains(data.card.skillNames, "v_chiling") and player:getMark("v_chiling_damage") > 0
      end
  end,
  --使用条件：
  -- 卡牌使用宣告后：需要askforcard（仅限手牌），存在且非虚拟牌则return true；
  -- 其他：return true
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardUseDeclared then
      local prompt = "v_chiling_card"
      local card = room:askForCard(player, 1, 1, false, self.name, true, ".", prompt)[1]
      if card and card > 0 then
        self.cost_data = card
        return true
      end
    else
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.AfterCardUseDeclared then
      room:sendLog{
        type = "#v_chiling_selected_log",
        from = player.id,
        arg = self.name,
        arg2 = 1,
      }
      local cid = self.cost_data
      room:setPlayerMark(player, "v_chiling_id", cid)
      local hand = player:getCardIds(Player.Hand)
      local hands = {}
      for _,p in ipairs(hand) do
        if p ~= cid then
          table.insert(hands, p)
        end
      end
      if #hands > 0 then
        player:showCards(hands)
        room:delay(500)
      end
    elseif event == fk.AfterCardsMove then
      room:setPlayerMark(player, "v_chiling_id", 0)
      room:setPlayerMark(player, "v_chiling_damage", 1)
    elseif event == fk.DamageCaused then
      data.damage = data.damage + 1
      room:setPlayerMark(player, "v_chiling_id", 0)
      room:setPlayerMark(player, "v_chiling_damage", 0)
    end
  end,

  refresh_events = {fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
      and (player:getMark("v_chiling_id") > 0 or player:getMark("v_chiling_damage") > 0)
      and data.card
      and data.card.name == "fire_attack"
      and data.card.skillName == "v_chiling"
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "v_chiling_id", 0)
    room:setPlayerMark(player, "v_chiling_damage", 0)
  end,
}
v_chiling:addRelatedSkill(v_chiling_next)

--------------------------------------------------
--离息
--------------------------------------------------

local v_lixi = fk.CreateTriggerSkill{
  name = "v_lixi",
  anim_type = "support",
  -- mute = true,
  -- 这是最接近离场的时机···
  events = {fk.AskForPeachesDone},
  can_trigger = function(self, event, target, player, data)
    if not (target == player and player:hasSkill(self)) then return false end
    local room = player.room
    local draw = room.draw_pile
    for _,p in ipairs(draw) do
    local card = Fk:getCardById(p)
      -- print(card.name)
      if card.name == "fan" then
        return true
      end
    end
  end,
  on_cost = function() return true end,
  on_use = function(self, event, target, player, data)
    return true
  end,
}

--------------------------------------------------
--角色特性：翼之涅槃
--耦合进aux_skill中
--------------------------------------------------

local v_characteristic_niepan = fk.CreateTriggerSkill{
  name = "#v_characteristic_niepan",
  anim_type = "special",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  -- events = {fk.GameStart, fk.Deathed},
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    if event == fk.GameStart then
      return player:hasSkill(self)
    -- elseif event == fk.Deathed then
    --   return target == player and player:hasSkill(self.name, true, true)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- if event == fk.GameStart then
    --   for _, p in ipairs(room:getAllPlayers()) do
    --     --这里后续可以加入特殊疲劳机制判定（例如秋凛子）
    --     if p:getMark("v_phoenix") == 0 
    --       and p:getMark("v_noexhaustion") == 0 
    --     then
    --       room:setPlayerMark(p, "v_phoenix", 1)
    --     end
    --   end
    -- elseif event == fk.Deathed then
    --   for _, p in ipairs(room:getAllPlayers()) do
    --     --这里后续可以加入特殊疲劳机制判定（例如秋凛子）
    --     if p:getMark("v_phoenix") > 0 then
    --       room:setPlayerMark(p, "v_phoenix", 0)
    --     end
    --   end
    -- end
  end,
}

--------------------------------------------------
--秋乌
--------------------------------------------------

local qiuwu_chiwuliuhuo = General(extension, "qiuwu_chiwuliuhuo", "individual", 3, 3, General.Bigender)
qiuwu_chiwuliuhuo:addSkill(v_chiling)
qiuwu_chiwuliuhuo:addSkill(v_lixi)
qiuwu_chiwuliuhuo:addSkill(v_characteristic_niepan)

--------------------------------------------------
--渴欲
--------------------------------------------------

local v_keyu = fk.CreateTriggerSkill{
  name = "v_keyu",
  --赋予防御型技能定义
  anim_type = "defensive",
  --时机：体力回复后
  events = {fk.HpRecover},
  --使用条件：
  --遍历到的角色具有本技能、触发时机的角色不为遍历到的角色；
  --...
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target ~= player
    and not target:isNude() and data.num > 0
    and player:usedSkillTimes(self.name, Player.HistoryRound) < 1
  end,
  -- 反正是默认的，先这么放着
  -- on_cost = function(self, event, target, player, data)
  --   return true
  -- end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if target ~= player then
      --doindicate的两个参数一个为integer，一个为table
      room:doIndicate(player.id, { target.id })
    end
    room:setPlayerMark(player, "@@v_keyu_used-round", 1)
    if not target:isNude() then
      local id = room:askForCardChosen(player, target, "he", self.name)
      local card = Fk:getCardById(id)
      target:showCards(card)
      room:moveCardTo(card, Player.Hand, player, fk.ReasonPrey, self.name, nil, true)
      if card and card.trueName == "slash" then
        room:loseHp(target, 1, self.name)
      end
    end
  end,
}

--------------------------------------------------
--纤柔
--FIXME:流失体力不触发
--------------------------------------------------

local v_xianrou_prohibit = fk.CreateProhibitSkill{
  name = "#v_xianrou_prohibit",
  --闪电这个版本还是能挂你脑门上的。
  is_prohibited = function(self, from, to, card)
    if to:hasSkill("v_xianrou") and from ~= to and card.suit == Card.Spade then
      return true
    end
  end,
}
local v_xianrou = fk.CreateTriggerSkill{
  name = "v_xianrou",
  --赋予防御型技能定义
  anim_type = "defensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：阶段变化时
  events = {fk.Damaged},
  --使用条件：
  --触发时机的角色为遍历到的角色、遍历到的角色具有本技能；
  --受到的伤害大于0，造成伤害的角色存在且存活，造成伤害的角色不为遍历到的角色。
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) 
    and data.damage > 0 and data.from and data.from:isAlive()
    and data.from ~= player
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = data.from
    local prompt = "v_xianrou_ask:"..player.id
    --doindicate的两个参数一个为integer，一个为table
    room:doIndicate(player.id, { tar.id })
    -- 这里原版存在一个caneffect询问
    local card = room:askForCard(tar, 1, 1, true, self.name, true, ".|.|spade", prompt)[1]
    if card then
      --交牌
      room:moveCardTo(card, Player.Hand, player, fk.ReasonGive, self.name, nil, true)
    else
      room:loseHp(tar, 1, self.name)
    end
  end,
}

v_xianrou:addRelatedSkill(v_xianrou_prohibit)

--------------------------------------------------
--芳乃推
--------------------------------------------------

local fangnaitui_yinyangmeiying = General(extension, "fangnaitui_yinyangmeiying", "individual", 3, 3, General.Bigender)
fangnaitui_yinyangmeiying:addSkill(v_keyu)
fangnaitui_yinyangmeiying:addSkill(v_xianrou)

--------------------------------------------------
--宵暗
--------------------------------------------------

local v_xiaoan = fk.CreateTriggerSkill{
  name = "v_xiaoan",
  anim_type = "defensive",
  events = {fk.CardEffectCancelledOut},
  --使用条件：
  --存在目标，目标为遍历到的角色，目标在场，目标具有本技能；
  --存在使用的牌。
  --(现在的写法可能导致)
  can_trigger = function(self, event, target, player, data)
    return data.to and player.id == data.to and player:isAlive() and player:hasSkill(self)
      and data.card
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    --后续这里可以加技能无法指定谁之类的判定在这里。
    -- local targets = table.map(room:getOtherPlayers(player), function(p) return p.id end)
    local fir_targets = table.map(room:getOtherPlayers(player), function(p) return p.id end)
    local targets = {}
    --这里后续可以加caneffect
    for _, pid in ipairs(fir_targets) do
      if VslUtil.SkillCanTarget(room:getPlayerById(pid), player, self.name) then
        table.insert(targets, pid)
      end
    end
    local to = room:askForChoosePlayers(player, targets, 1, 1, "@v_xiaoan_ask", self.name, true)
    --后续这里可以加技能失效的判定在这里。
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tar = room:getPlayerById(self.cost_data)
    local judge = {
      who = tar,
      reason = self.name,
      pattern = ".|.|spade,club,diamond",
    }
    room:judge(judge)
    local result = judge.card
    if result.suit == Card.Spade then
      room:damage{
        from = player,
        to = tar,
        damage = 1,
        damageType = fk.ThunderDamage,
        skillName = self.name,
      }
    elseif result.suit == Card.Club then
      room:damage{
        from = player,
        to = tar,
        damage = 1,
        damageType = fk.IceDamage,
        skillName = self.name,
      }
    elseif result.suit == Card.Diamond then
      room:damage{
        from = player,
        to = tar,
        damage = 1,
        damageType = fk.FireDamage,
        skillName = self.name,
      }
    -- elseif result.suit == Card.Heart then
    --   room:damage{
    --     from = player,
    --     to = tar,
    --     damage = 1,
    --     damageType = fk.ThunderDamage,
    --     skillName = self.name,
    --   }
    --   room:damage{
    --     from = player,
    --     to = tar,
    --     damage = 1,
    --     damageType = fk.IceDamage,
    --     skillName = self.name,
    --   }
    --   room:damage{
    --     from = player,
    --     to = tar,
    --     damage = 1,
    --     damageType = fk.FireDamage,
    --     skillName = self.name,
    --   }
    end
  end,
}

--------------------------------------------------
--绝断
--------------------------------------------------

local v_jueduan = fk.CreateTriggerSkill{
  --（刚需）技能认证名
  name = "v_jueduan",
  --(非必要）赋予进攻型技能定义
  anim_type = "offensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：受到伤害时，造成伤害时
  events = {fk.DamageCaused},
  --触发条件：
  --触发时机的角色为遍历到的角色、遍历到的角色具有本技能、造成的伤害大于0；
  --非普通伤害
  --受到伤害的角色存在且存活（未完成）
  --遍历到的角色装备区牌数小于受到伤害的角色装备区牌数（未完成）
  --(后续补充)非光伤
  can_trigger = function(self, event, target, player, data)
    if not (target == player and player:hasSkill(self) and
      data.damage > 0 and data.damageType ~= fk.NormalDamage and
      data.to and data.to:isAlive() and
      #player:getCardIds(Player.Equip) < #data.to:getCardIds(Player.Equip)) then 
      return false
    end
    return true
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage + 1
  end,
}

--------------------------------------------------
--能美枫铃
--------------------------------------------------

local nengmeifengling_lanmeiyushi = General(extension, "nengmeifengling_lanmeiyushi", "individual", 3, 3, General.Bigender)
nengmeifengling_lanmeiyushi:addSkill(v_xiaoan)
nengmeifengling_lanmeiyushi:addSkill(v_jueduan)

--------------------------------------------------
--芸芸
--------------------------------------------------

local v_yunyun = fk.CreateTriggerSkill{
  name = "v_yunyun",
  --赋予摸牌型技能定义
  anim_type = "drawcard",
  -- --时机：手牌结算后
  -- events = {fk.CardUseFinished},
  --时机：宣告手牌使用时
  events = {fk.AfterCardUseDeclared, fk.CardResponding},
  --触发条件：
  --触发时机的角色为遍历到的角色、遍历到的角色具有本技能
  --本回合此技能触发次数<1
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
      and player:usedSkillTimes(self.name, Player.HistoryTurn) < 1
      and (not player:isNude())
  end,
  --使用条件：
  -- 卡牌使用宣告后：需要askforcard，存在且非虚拟牌则return true；
  -- 其他：return true
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local prompt = "@v_yunyun_recast"
    local card = room:askForCard(player, 1, 1, true, self.name, true, ".", prompt)[1]
    if card and card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local car = self.cost_data
    room:recastCard(car, player, self.name)
  end,
}

--------------------------------------------------
--欣荣
--------------------------------------------------

local v_xinrong = fk.CreateTriggerSkill{
  name = "v_xinrong",
  --赋予摸牌型技能定义
  anim_type = "drawcard",
  --时机：阶段开始时
  events = {fk.EventPhaseStart},
  --触发条件：
  --触发时机的角色为遍历到的角色；
  --遍历到的角色处于结束阶段：遍历到的角色在场且具有本技能（具有本技能就够了，hasskill自己会判断的），遍历到的角色getlosthp>0
  --遍历到的角色处于准备阶段：遍历到的角色欣荣mark大于0
  can_trigger = function(self, event, target, player, data)
    --阶段变化时，实现“是否跳出牌”的效果。
    --exist_or_not：用来确认是否跳过对应阶段，类似于以前的Player:isSkipped()
    if target == player then
      if player.phase == Player.Finish then
        return player:hasSkill(self) and player:getLostHp() > 0
      elseif player.phase == Player.Start then
        return player:getMark("v_xinrong_used") > 0
      end
    end
  end,
  --使用条件：
  --遍历到的角色处于结束阶段：askforskillinvoke
  --遍历到的角色处于准备阶段：return true
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if (player.phase == Player.Finish and room:askForSkillInvoke(player, self.name, data)) 
      or player.phase == Player.Start then
      return true
    end
  end,
  --使用效果：
  --遍历到的角色处于结束阶段：设立X，作为标记，恢复等量体力，摸等量张牌，摸牌时候为每一张牌提供cardmark
  --遍历到的角色处于准备阶段：清理标记，失去体力，跑一遍手里的牌，如果有cardmark就弃置
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player.phase == Player.Finish then
      room:setPlayerMark(player, "v_xinrong_used", 1)
      local X = math.min(player:getLostHp(), #room:getAlivePlayers())
      if X > 0 then
        room:recover{
          who = player,
          num = X,
          recoverBy = player,
          skillName = self.name,
        }
        room:setPlayerMark(player, "@v_xinrong", X)
      end
      local cards = player:drawCards(X, self.name)
      player:showCards(cards)
      for _,id in ipairs(cards) do
        room:setPlayerMark(player, "v_xinrong_card_"..id, 1)
        room:setCardMark(Fk:getCardById(id), "@@v_xinrong-cm!dc*", 1)
      end
    elseif player.phase == Player.Start then
      local allcards = {}
      local throw_cards = {}
      room:setPlayerMark(player, "v_xinrong_used", 0)
      if player:getMark("@v_xinrong") > 0 then
        room:loseHp(player, player:getMark("@v_xinrong"), self.name)
        room:setPlayerMark(player, "@v_xinrong", 0)
      end
      for _,mark in ipairs(player:getMarkNames()) do
        if string.sub(mark, 1, 15) == "v_xinrong_card_" and player:getMark(mark) > 0 then
          local id = tonumber(string.sub(mark, 16, -1))
          table.insertTable(allcards, target:getCardIds(Player.Hand))
          table.insertTable(allcards, target:getCardIds(Player.Equip))
          for _,cid in ipairs(allcards) do
            if cid == id then
              table.insertIfNeed(throw_cards, cid)
            end
          end
          room:setPlayerMark(player, mark, 0)
        end
      end
      if #throw_cards > 0 then
        room:throwCard(throw_cards, self.name, player, player)
      end
    end
  end,
}

--------------------------------------------------
--哈娜
--------------------------------------------------

local hana_menglufanhua = General(extension, "hana_menglufanhua", "individual", 4, 4, General.Female)
hana_menglufanhua:addSkill(v_yunyun)
hana_menglufanhua:addSkill(v_xinrong)
-- hana_menglufanhua:addSkill(v_cheat)

--------------------------------------------------
--冰沙
--------------------------------------------------

local v_bingsha = fk.CreateTriggerSkill{
  name = "v_bingsha",
  --赋予支援型技能定义
  anim_type = "support",
  --时机：阶段变化时，宣告手牌使用时
  events = {fk.EventPhaseChanging, fk.AfterCardUseDeclared},
  --触发条件（已完成）：
  --遍历到的角色存在此技能。
  --  阶段变化时：
  --    触发时机的角色为遍历到的角色；（已完成）
  --    将进入出牌阶段；（已完成）
  --    未跳过出牌阶段；（已完成）
  --  宣告手牌使用时：（已完成）
  --    触发时机的角色不为遍历到的角色
  --    存在牌；牌的名字为“冰杀”
  --    一种我暂时不确定情况但是在曹操的奸雄里用到的机制: 牌在处理区时【弃牌区是否需要另议】，牌为虚拟/实体牌
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if not player:hasSkill(self) then return false end
    if event == fk.EventPhaseChanging then
      return target == player
      and data.to == Player.Draw and VslUtil.exist_or_not(player, Player.Draw)
    elseif event == fk.AfterCardUseDeclared then
      return target ~= player and data.card 
      -- and data.card.trueName == "slash" 
      and data.card.name == "v_ice__slash" and
      table.every(data.card:isVirtual() and data.card.subcards or {data.card.id}, function(id) return room:getCardArea(id) == Card.Processing end)
    end
  end,
  --使用条件（已完成）：
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseChanging then
      if room:askForSkillInvoke(player, self.name, data) then
        return true
      end
    --满足技能发动要求后，锁定发动。
    elseif event == fk.AfterCardUseDeclared then
      return true
    end
  end,
  --使用效果（未完成）：
  --阶段变化时：
  --  检索牌堆中的桃，获得其中随机一张。（已完成）
  --宣告手牌使用时：
  --  获得之。
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseChanging then
      --获取牌堆中的"桃"。
      local allcards = {}
      table.insertTable(allcards, room.draw_pile)
      local peaches = table.filter(allcards, function(id)
        local card = Fk:getCardById(id)
        return card.name == "peach"
      end)
      if #peaches > 0 then
        local x = #peaches
        local c = math.random(1, x)
        local cid = peaches[c]
        --这种函数可以从表中随机选n个元素并返回一张表，如果n是nil，那么返回的就不是表而是单个元素
        --local card = table.random(peaches, nil)
        local address = "./packages/"..VslUtil.extensionName.."/image/skill/lixingyu"..math.random(1,2)
        room:setEmotion(player, address)
        room:obtainCard(player, cid, true, fk.ReasonPrey)
      else
        room:sendLog{
          type = "#v_skill_find_fail",
          arg = self.name,
          arg2 = "peach",
        }
      end
      return true
    --满足技能发动要求后，锁定发动。
    elseif event == fk.AfterCardUseDeclared then
      local address = "./packages/"..VslUtil.extensionName.."/image/skill/lixingyu"..math.random(5,6)
      room:setEmotion(player, address)
      room:obtainCard(player.id, data.card, true, fk.ReasonPrey)
    end
  end,
}

--------------------------------------------------
--冰身
--------------------------------------------------

local v_bingshen = fk.CreateTriggerSkill{
  name = "v_bingshen",
  --赋予防御型技能定义
  anim_type = "defensive",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：指定目标时，受到伤害时
  events = {fk.TargetSpecified, fk.DamageInflicted},
  --触发条件（已完成）：
  --遍历到的角色存在此技能。
  --  指定目标时：
  --    遍历到的角色未装备防具；存在牌，且牌的truename为“杀”；
  --    卡的颜色为黑色
  --    牌的目标存在，牌的目标中存在遍历到的角色
  --    本次流程中第一次触发这个时机（待定）
  --  受到伤害时：
  --    触发时机的角色为遍历到的角色；受到的伤害大于0，受到的伤害为火焰伤害
  can_trigger = function(self, event, target, player, data)
    -- local room = player.room
    -- local pla = room:getPlayerById(data.from)
    if not player:hasSkill(self) then return false end
    if event == fk.TargetSpecified then
      local target_contain_player = false
      for _, p in ipairs(AimGroup:getAllTargets(data.tos)) do
        if p == player.id then
          target_contain_player = true
        end
      end
      return not player:getEquipment(Card.SubtypeArmor)
      and data.card and data.card.trueName == "slash" 
      and data.card.color == Card.Black
      -- and pla and pla:isAlive() and pla ~= player
      and #AimGroup:getAllTargets(data.tos) > 0 and target_contain_player
      and data.firstTarget
    elseif event == fk.DamageInflicted then
      return target == player 
      and data.damage > 0 and data.damageType == fk.FireDamage
    end
  end,
  --使用效果（已完成）：
  --  指定目标时：
  --    如果非冰杀，播放表情（已完成）
  --    令杀无效化（已完成）
  --  受到伤害时：
  --    发送表情；伤害+1（已完成）
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecified then
      if not data.card.name == "v_ice__slash" then
        local address = "./packages/"..VslUtil.extensionName.."/image/skill/lixingyu"..math.random(3,4)
        room:setEmotion(player, address)
      end
      table.insert(data.nullifiedTargets, player.id)
      room:sendLog{
        type = "#v_bingshen",
        from = player.id,
        arg = self.name,
        -- arg2 = data.damage,
      }
    elseif event == fk.DamageInflicted then
      local address = "./packages/"..VslUtil.extensionName.."/image/skill/lixingyu"..math.random(7,9)
      room:setEmotion(player, address)
      data.damage = data.damage + 1
    end
  end,
}

--------------------------------------------------
--角色特性：一起恰冰沙
--------------------------------------------------

local v_characteristic_yiqiqiabingsha = fk.CreateTriggerSkill{
  name = "#v_characteristic_yiqiqiabingsha",
  anim_type = "special",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  events = {fk.GameStart},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self.name, true) then
      return false
    end
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      local cids = {}
      -- for i = #room.void, 1, -1 do
      --   if Fk:getCardById(room.void[i]).name == "raid_and_frontal_attack" then
      --     local idRemoved = table.remove(room.void, i)
      --     table.insert(room.draw_pile, math.random(1, #room.draw_pile), idRemoved)
      --     room:setCardArea(idRemoved, Card.DrawPile, nil)
      --   end
      -- end
      for i = 1, 3, 1 do
        local card = room:printCard("v_ice__slash", Card.Club, i)
        table.insertIfNeed(cids, card.id)
      end
      local ram = math.random(1, #room.draw_pile + 1)
      room:moveCards({
        ids = cids,
        toArea = Card.DrawPile,
        moveReason = fk.ReasonJustMove,
        skillName = self.name,
        drawPilePosition = ram,
      })
      room:sendLog{
				type = "#v_newcardintopile_log",
				from = player.id,
				card = cids,
				arg = self.name,
			} 
      room:doBroadcastNotify("UpdateDrawPile", #room.draw_pile)
    end
  end,
}

--------------------------------------------------
--璃星羽
--------------------------------------------------

local lixingyu_bingshayoulang = General(extension, "lixingyu_bingshayoulang", "individual", 4, 4, General.Bigender)
lixingyu_bingshayoulang:addSkill(v_bingsha)
lixingyu_bingshayoulang:addSkill(v_bingshen)
lixingyu_bingshayoulang:addSkill(v_characteristic_yiqiqiabingsha)

-- 加载本包的翻译包(load translations of this package)，这一步在本文档的最后进行。
-- dofile "packages/vupslash/i18n/init.lua"
dofile "packages/VslTest/i18n/init.lua"

-- return { extension } 

return extension
